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/rendering/FastTextAutosizer.h"
37 #include "core/rendering/HitTestLocation.h"
38 #include "core/rendering/LayoutRepainter.h"
39 #include "core/rendering/RenderFlowThread.h"
40 #include "core/rendering/RenderLayer.h"
41 #include "core/rendering/RenderMultiColumnFlowThread.h"
42 #include "core/rendering/RenderText.h"
43 #include "core/rendering/RenderView.h"
44 #include "core/rendering/line/LineWidth.h"
45 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
46 #include "platform/text/BidiTextRun.h"
52 bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
54 struct SameSizeAsMarginInfo {
56 LayoutUnit margins[2];
59 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
62 // Collapsing flags for whether we can collapse our margins with our children's margins.
63 bool m_canCollapseWithChildren : 1;
64 bool m_canCollapseMarginBeforeWithChildren : 1;
65 bool m_canCollapseMarginAfterWithChildren : 1;
66 bool m_canCollapseMarginAfterWithLastChild: 1;
68 // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
69 // margins in our container. Table cells and the body are the common examples. We
70 // also have a custom style property for Safari RSS to deal with TypePad blog articles.
71 bool m_quirkContainer : 1;
73 // This flag tracks whether we are still looking at child margins that can all collapse together at the beginning of a block.
74 // They may or may not collapse with the top margin of the block (|m_canCollapseTopWithChildren| tells us that), but they will
75 // always be collapsing with one another. This variable can remain set to true through multiple iterations
76 // as long as we keep encountering self-collapsing blocks.
77 bool m_atBeforeSideOfBlock : 1;
79 // This flag is set when we know we're examining bottom margins and we know we're at the bottom of the block.
80 bool m_atAfterSideOfBlock : 1;
82 // These variables are used to detect quirky margins that we need to collapse away (in table cells
83 // and in the body element).
84 bool m_hasMarginBeforeQuirk : 1;
85 bool m_hasMarginAfterQuirk : 1;
86 bool m_determinedMarginBeforeQuirk : 1;
88 bool m_discardMargin : 1;
90 // These flags track the previous maximal positive and negative margins.
91 LayoutUnit m_positiveMargin;
92 LayoutUnit m_negativeMargin;
95 MarginInfo(RenderBlockFlow*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
97 void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
98 void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
101 m_positiveMargin = 0;
102 m_negativeMargin = 0;
104 void setHasMarginBeforeQuirk(bool b) { m_hasMarginBeforeQuirk = b; }
105 void setHasMarginAfterQuirk(bool b) { m_hasMarginAfterQuirk = b; }
106 void setDeterminedMarginBeforeQuirk(bool b) { m_determinedMarginBeforeQuirk = b; }
107 void setPositiveMargin(LayoutUnit p) { ASSERT(!m_discardMargin); m_positiveMargin = p; }
108 void setNegativeMargin(LayoutUnit n) { ASSERT(!m_discardMargin); m_negativeMargin = n; }
109 void setPositiveMarginIfLarger(LayoutUnit p)
111 ASSERT(!m_discardMargin);
112 if (p > m_positiveMargin)
113 m_positiveMargin = p;
115 void setNegativeMarginIfLarger(LayoutUnit n)
117 ASSERT(!m_discardMargin);
118 if (n > m_negativeMargin)
119 m_negativeMargin = n;
122 void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
123 void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
124 void setCanCollapseMarginAfterWithLastChild(bool collapse) { m_canCollapseMarginAfterWithLastChild = collapse; }
125 void setDiscardMargin(bool value) { m_discardMargin = value; }
127 bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
128 bool canCollapseWithMarginBefore() const { return m_atBeforeSideOfBlock && m_canCollapseMarginBeforeWithChildren; }
129 bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
130 bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
131 bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
132 bool canCollapseMarginAfterWithLastChild() const { return m_canCollapseMarginAfterWithLastChild; }
133 bool quirkContainer() const { return m_quirkContainer; }
134 bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
135 bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
136 bool hasMarginAfterQuirk() const { return m_hasMarginAfterQuirk; }
137 LayoutUnit positiveMargin() const { return m_positiveMargin; }
138 LayoutUnit negativeMargin() const { return m_negativeMargin; }
139 bool discardMargin() const { return m_discardMargin; }
140 LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
142 static bool inNormalFlow(RenderBox* child)
144 RenderBlock* curr = child->containingBlock();
145 RenderView* renderView = child->view();
146 while (curr && curr != renderView) {
147 if (curr->hasColumns() || curr->isRenderFlowThread())
149 if (curr->isFloatingOrOutOfFlowPositioned())
151 curr = curr->containingBlock();
156 RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
159 COMPILE_ASSERT(sizeof(MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
162 RenderBlockFlow::~RenderBlockFlow()
166 RenderBlockFlow* RenderBlockFlow::createAnonymous(Document* document)
168 RenderBlockFlow* renderer = new RenderBlockFlow(0);
169 renderer->setDocumentForAnonymous(document);
173 RenderObject* RenderBlockFlow::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
175 RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread();
178 setLogicalTopForChild(flowThread, borderBefore() + paddingBefore());
179 flowThread->layoutColumns(relayoutChildren, layoutScope);
180 determineLogicalLeftPositionForChild(flowThread);
184 bool RenderBlockFlow::updateLogicalWidthAndColumnWidth()
186 bool relayoutChildren = RenderBlock::updateLogicalWidthAndColumnWidth();
187 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
188 if (flowThread->computeColumnCountAndWidth())
191 return relayoutChildren;
194 void RenderBlockFlow::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
196 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
197 LogicalExtentComputedValues computedValues;
198 computeLogicalHeight(LayoutUnit(), logicalTop(), computedValues);
199 LayoutUnit columnHeight = computedValues.m_extent - borderAndPaddingLogicalHeight() - scrollbarLogicalHeight();
200 pageLogicalHeightChanged = columnHeight != flowThread->columnHeightAvailable();
201 flowThread->setColumnHeightAvailable(std::max<LayoutUnit>(columnHeight, 0));
202 } else if (hasColumns()) {
203 ColumnInfo* colInfo = columnInfo();
205 if (!pageLogicalHeight) {
206 LayoutUnit oldLogicalHeight = logicalHeight();
208 // We need to go ahead and set our explicit page height if one exists, so that we can
209 // avoid doing two layout passes.
210 updateLogicalHeight();
211 LayoutUnit columnHeight = contentLogicalHeight();
212 if (columnHeight > 0) {
213 pageLogicalHeight = columnHeight;
214 hasSpecifiedPageLogicalHeight = true;
216 setLogicalHeight(oldLogicalHeight);
218 if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
219 colInfo->setColumnHeight(pageLogicalHeight);
220 pageLogicalHeightChanged = true;
223 if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
224 colInfo->clearForcedBreaks();
225 } else if (isRenderFlowThread()) {
226 RenderFlowThread* flowThread = toRenderFlowThread(this);
228 // FIXME: This is a hack to always make sure we have a page logical height, if said height
229 // is known. The page logical height thing in LayoutState is meaningless for flow
230 // thread-based pagination (page height isn't necessarily uniform throughout the flow
231 // thread), but as long as it is used universally as a means to determine whether page
232 // height is known or not, we need this. Page height is unknown when column balancing is
233 // enabled and flow thread height is still unknown (i.e. during the first layout pass). When
234 // it's unknown, we need to prevent the pagination code from assuming page breaks everywhere
235 // and thereby eating every top margin. It should be trivial to clean up and get rid of this
236 // hack once the old multicol implementation is gone.
237 pageLogicalHeight = flowThread->isPageLogicalHeightKnown() ? LayoutUnit(1) : LayoutUnit(0);
239 pageLogicalHeightChanged = flowThread->pageLogicalSizeChanged();
243 bool RenderBlockFlow::shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const
245 // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
246 // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
247 ColumnInfo* colInfo = columnInfo();
248 LayoutUnit columnHeight = pageLogicalHeight;
249 const int minColumnCount = colInfo->forcedBreaks() + 1;
250 const int desiredColumnCount = colInfo->desiredColumnCount();
251 if (minColumnCount >= desiredColumnCount) {
252 // The forced page breaks are in control of the balancing. Just set the column height to the
253 // maximum page break distance.
254 if (!pageLogicalHeight) {
255 LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
256 view()->layoutState()->pageLogicalOffset(*this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
257 columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
259 } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
260 // Now that we know the intrinsic height of the columns, we have to rebalance them.
261 columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf(layoutOverflowLogicalBottom.toFloat() / desiredColumnCount));
264 if (columnHeight && columnHeight != pageLogicalHeight) {
265 pageLogicalHeight = columnHeight;
272 void RenderBlockFlow::setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight)
274 ColumnInfo* colInfo = columnInfo();
275 if (pageLogicalHeight)
276 colInfo->setColumnCountAndHeight(count, pageLogicalHeight);
278 if (columnCount(colInfo)) {
279 setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
284 bool RenderBlockFlow::isSelfCollapsingBlock() const
286 m_hasOnlySelfCollapsingChildren = RenderBlock::isSelfCollapsingBlock();
287 return m_hasOnlySelfCollapsingChildren;
290 void RenderBlockFlow::layoutBlock(bool relayoutChildren)
292 ASSERT(needsLayout());
293 ASSERT(isInlineBlockOrInlineTable() || !isInline());
295 // If we are self-collapsing with self-collapsing descendants this will get set to save us burrowing through our
296 // descendants every time in |isSelfCollapsingBlock|. We reset it here so that |isSelfCollapsingBlock| attempts to burrow
297 // at least once and so that it always gives a reliable result reflecting the latest layout.
298 m_hasOnlySelfCollapsingChildren = false;
300 if (!relayoutChildren && simplifiedLayout())
303 SubtreeLayoutScope layoutScope(*this);
305 // Multiple passes might be required for column and pagination based layout
306 // In the case of the old column code the number of passes will only be two
307 // however, in the newer column code the number of passes could equal the
308 // number of columns.
310 LayoutUnit pageLogicalHeight = 0;
311 LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
313 done = layoutBlockFlow(relayoutChildren, pageLogicalHeight, layoutScope);
315 fitBorderToLinesIfNeeded();
317 RenderView* renderView = view();
318 if (renderView->layoutState()->pageLogicalHeight())
319 setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(*this, logicalTop()));
321 updateLayerTransform();
323 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
324 // we overflow or not.
325 updateScrollInfoAfterLayout();
327 // Repaint with our new bounds if they are different from our old bounds.
328 bool didFullRepaint = repainter.repaintAfterLayout();
329 if (!didFullRepaint && m_repaintLogicalTop != m_repaintLogicalBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
330 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
331 setShouldRepaintOverflow(true);
338 inline bool RenderBlockFlow::layoutBlockFlow(bool relayoutChildren, LayoutUnit &pageLogicalHeight, SubtreeLayoutScope& layoutScope)
340 LayoutUnit oldLeft = logicalLeft();
341 if (updateLogicalWidthAndColumnWidth())
342 relayoutChildren = true;
344 rebuildFloatsFromIntruding();
346 bool pageLogicalHeightChanged = false;
347 bool hasSpecifiedPageLogicalHeight = false;
348 checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
349 if (pageLogicalHeightChanged)
350 relayoutChildren = true;
352 LayoutStateMaintainer statePusher(*this, locationOffset(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
354 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
355 // our current maximal positive and negative margins. These values are used when we
356 // are collapsed with adjacent blocks, so for example, if you have block A and B
357 // collapsing together, then you'd take the maximal positive margin from both A and B
358 // and subtract it from the maximal negative margin from both A and B to get the
359 // true collapsed margin. This algorithm is recursive, so when we finish layout()
360 // our block knows its current maximal positive/negative values.
362 // Start out by setting our margin values to our current margins. Table cells have
363 // no margins, so we don't fill in the values for table cells.
364 if (!isTableCell()) {
365 initMaxMarginValues();
366 setHasMarginBeforeQuirk(style()->hasMarginBeforeQuirk());
367 setHasMarginAfterQuirk(style()->hasMarginAfterQuirk());
368 setPaginationStrut(0);
371 LayoutUnit beforeEdge = borderBefore() + paddingBefore();
372 LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
373 LayoutUnit previousHeight = logicalHeight();
374 setLogicalHeight(beforeEdge);
376 m_repaintLogicalTop = 0;
377 m_repaintLogicalBottom = 0;
378 if (!firstChild() && !isAnonymousBlock())
379 setChildrenInline(true);
381 FastTextAutosizer::LayoutScope fastTextAutosizerLayoutScope(this);
383 if (childrenInline())
384 layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom, afterEdge);
386 layoutBlockChildren(relayoutChildren, layoutScope, beforeEdge, afterEdge);
388 // Expand our intrinsic height to encompass floats.
389 if (lowestFloatLogicalBottom() > (logicalHeight() - afterEdge) && createsBlockFormattingContext())
390 setLogicalHeight(lowestFloatLogicalBottom() + afterEdge);
392 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
393 if (flowThread->recalculateColumnHeights()) {
394 setChildNeedsLayout(MarkOnlyThis);
397 } else if (hasColumns()) {
398 OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
399 if (childrenInline())
400 addOverflowFromInlineChildren();
402 addOverflowFromBlockChildren();
403 LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
404 m_overflow = savedOverflow.release();
406 if (!hasSpecifiedPageLogicalHeight && shouldRelayoutForPagination(pageLogicalHeight, layoutOverflowLogicalBottom)) {
407 setEverHadLayout(true);
411 setColumnCountAndHeight(ceilf(layoutOverflowLogicalBottom.toFloat() / pageLogicalHeight.toFloat()), pageLogicalHeight.toFloat());
414 if (shouldBreakAtLineToAvoidWidow()) {
415 setEverHadLayout(true);
419 // Calculate our new height.
420 LayoutUnit oldHeight = logicalHeight();
421 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
423 updateLogicalHeight();
424 LayoutUnit newHeight = logicalHeight();
425 if (oldHeight > newHeight && !childrenInline()) {
426 // One of our children's floats may have become an overhanging float for us.
427 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
428 if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
429 RenderBlockFlow* block = toRenderBlockFlow(child);
430 if (block->lowestFloatLogicalBottom() + block->logicalTop() <= newHeight)
432 addOverhangingFloats(block, false);
437 bool heightChanged = (previousHeight != newHeight);
439 relayoutChildren = true;
441 layoutPositionedObjects(relayoutChildren || isDocumentElement(), oldLeft != logicalLeft() ? ForcedLayoutAfterContainingBlockMoved : DefaultLayout);
443 computeRegionRangeForBlock(flowThreadContainingBlock());
445 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
446 computeOverflow(oldClientAfterEdge);
451 void RenderBlockFlow::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
453 LayoutUnit startPosition = borderStart() + paddingStart();
454 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
455 startPosition -= verticalScrollbarWidth();
456 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
458 // Add in our start margin.
459 LayoutUnit childMarginStart = marginStartForChild(child);
460 LayoutUnit newPosition = startPosition + childMarginStart;
462 // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats. They need
463 // to shift over as necessary to dodge any floats that might get in the way.
464 if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
465 newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
467 setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
470 void RenderBlockFlow::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
472 if (isHorizontalWritingMode()) {
473 if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
474 view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
475 child->setX(logicalLeft);
477 if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
478 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
479 child->setY(logicalLeft);
483 void RenderBlockFlow::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
485 if (isHorizontalWritingMode()) {
486 if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
487 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
488 child->setY(logicalTop);
490 if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
491 view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
492 child->setX(logicalTop);
496 void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom)
498 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
499 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
501 // The child is a normal flow object. Compute the margins we will use for collapsing now.
502 child->computeAndSetBlockDirectionMargins(this);
504 // Try to guess our correct logical top position. In most cases this guess will
505 // be correct. Only if we're wrong (when we compute the real logical top position)
506 // will we have to potentially relayout.
507 LayoutUnit estimateWithoutPagination;
508 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
510 // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
511 LayoutRect oldRect = child->frameRect();
512 LayoutUnit oldLogicalTop = logicalTopForChild(child);
515 LayoutSize oldLayoutDelta = RuntimeEnabledFeatures::repaintAfterLayoutEnabled() ? LayoutSize() : view()->layoutDelta();
517 // Go ahead and position the child as though it didn't collapse with the top.
518 setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
520 RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
521 RenderBlockFlow* childRenderBlockFlow = (childRenderBlock && child->isRenderBlockFlow()) ? toRenderBlockFlow(child) : 0;
522 bool markDescendantsWithFloats = false;
523 if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats()) {
524 markDescendantsWithFloats = true;
525 } else if (UNLIKELY(logicalTopEstimate.mightBeSaturated())) {
526 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
527 // very large elements. If it does the comparison with oldLogicalTop might yield a
528 // false negative as adding and removing margins, borders etc from a saturated number
529 // might yield incorrect results. If this is the case always mark for layout.
530 markDescendantsWithFloats = true;
531 } else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
532 // If an element might be affected by the presence of floats, then always mark it for
534 LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
535 if (fb > logicalTopEstimate)
536 markDescendantsWithFloats = true;
539 if (childRenderBlockFlow) {
540 if (markDescendantsWithFloats)
541 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
542 if (!child->isWritingModeRoot())
543 previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
546 SubtreeLayoutScope layoutScope(*child);
547 if (!child->needsLayout())
548 child->markForPaginationRelayoutIfNeeded(layoutScope);
550 bool childHadLayout = child->everHadLayout();
551 bool childNeededLayout = child->needsLayout();
552 if (childNeededLayout)
555 // Cache if we are at the top of the block right now.
556 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
557 bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
559 // Now determine the correct ypos based off examination of collapsing margin
561 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo, childIsSelfCollapsing);
563 // Now check for clear.
564 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear, childIsSelfCollapsing);
566 bool paginated = view()->layoutState()->isPaginated();
568 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
569 atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
572 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
574 // Now we have a final top position. See if it really does end up being different from our estimate.
575 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
576 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
577 if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
578 SubtreeLayoutScope layoutScope(*child);
579 if (child->shrinkToAvoidFloats()) {
580 // The child's width depends on the line width.
581 // When the child shifts to clear an item, its width can
582 // change (because it has more available line width).
583 // So go ahead and mark the item as dirty.
584 layoutScope.setChildNeedsLayout(child);
587 if (childRenderBlock) {
588 if (!child->avoidsFloats() && childRenderBlock->containsFloats())
589 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
590 if (!child->needsLayout())
591 child->markForPaginationRelayoutIfNeeded(layoutScope);
594 // Our guess was wrong. Make the child lay itself out again.
595 child->layoutIfNeeded();
598 // If we previously encountered a self-collapsing sibling of this child that had clearance then
599 // we set this bit to ensure we would not collapse the child's margins, and those of any subsequent
600 // self-collapsing siblings, with our parent. If this child is not self-collapsing then it can
601 // collapse its margins with the parent so reset the bit.
602 if (!marginInfo.canCollapseMarginAfterWithLastChild() && !childIsSelfCollapsing)
603 marginInfo.setCanCollapseMarginAfterWithLastChild(true);
605 // We are no longer at the top of the block if we encounter a non-empty child.
606 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
607 if (marginInfo.atBeforeSideOfBlock() && !childIsSelfCollapsing)
608 marginInfo.setAtBeforeSideOfBlock(false);
610 // Now place the child in the correct left position
611 determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
613 LayoutSize childOffset = child->location() - oldRect.location();
615 // Update our height now that the child has been placed in the correct position.
616 setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
617 if (mustSeparateMarginAfterForChild(child)) {
618 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
619 marginInfo.clearMargin();
621 // If the child has overhanging floats that intrude into following siblings (or possibly out
622 // of this block), then the parent gets notified of the floats now.
623 if (childRenderBlockFlow)
624 addOverhangingFloats(childRenderBlockFlow, !childNeededLayout);
626 if (childOffset.width() || childOffset.height()) {
627 if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
628 view()->addLayoutDelta(childOffset);
630 // If the child moved, we have to repaint it as well as any floating/positioned
631 // descendants. An exception is if we need a layout. In this case, we know we're going to
632 // repaint ourselves (and the child) anyway.
633 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && childHadLayout && !selfNeedsLayout())
634 child->repaintOverhangingFloats(true);
635 else if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
636 child->repaintDuringLayoutIfMoved(oldRect);
639 if (!childHadLayout && child->checkForRepaint()) {
640 if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
642 child->repaintOverhangingFloats(true);
646 // Check for an after page/column break.
647 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
648 if (newHeight != height())
649 setLogicalHeight(newHeight);
652 if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
653 ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
657 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
659 RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
661 if (estimateWithoutPagination != logicalTopAfterClear) {
662 // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
664 setLogicalHeight(logicalTopAfterClear);
665 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
667 if (child->shrinkToAvoidFloats()) {
668 // The child's width depends on the line width.
669 // When the child shifts to clear an item, its width can
670 // change (because it has more available line width).
671 // So go ahead and mark the item as dirty.
672 child->setChildNeedsLayout(MarkOnlyThis);
675 SubtreeLayoutScope layoutScope(*child);
677 if (childRenderBlock) {
678 if (!child->avoidsFloats() && childRenderBlock->containsFloats())
679 toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
680 if (!child->needsLayout())
681 child->markForPaginationRelayoutIfNeeded(layoutScope);
684 // Our guess was wrong. Make the child lay itself out again.
685 child->layoutIfNeeded();
688 LayoutUnit oldTop = logicalTopAfterClear;
690 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
691 LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
693 if (pageLogicalHeightForOffset(result)) {
694 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
695 LayoutUnit spaceShortage = child->logicalHeight() - remainingLogicalHeight;
696 if (spaceShortage > 0) {
697 // If the child crosses a column boundary, report a break, in case nothing inside it has already
698 // done so. The column balancer needs to know how much it has to stretch the columns to make more
699 // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
700 // This should be improved, though, because here we just pretend that the child is
701 // unsplittable. A splittable child, on the other hand, has break opportunities at every position
702 // where there's no child content, border or padding. In other words, we risk stretching more
704 setPageBreak(result, spaceShortage);
708 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
709 LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
710 LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
712 LayoutUnit paginationStrut = 0;
713 LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
714 if (unsplittableAdjustmentDelta)
715 paginationStrut = unsplittableAdjustmentDelta;
716 else if (childRenderBlock && childRenderBlock->paginationStrut())
717 paginationStrut = childRenderBlock->paginationStrut();
719 if (paginationStrut) {
720 // We are willing to propagate out to our parent block as long as we were at the top of the block prior
721 // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
722 if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
723 // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
724 // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
725 // and pushes to the next page anyway, so not too concerned about it.
726 setPaginationStrut(result + paginationStrut);
727 if (childRenderBlock)
728 childRenderBlock->setPaginationStrut(0);
730 result += paginationStrut;
734 // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
735 setLogicalHeight(logicalHeight() + (result - oldTop));
737 // Return the final adjusted logical top.
741 void RenderBlockFlow::rebuildFloatsFromIntruding()
743 if (m_floatingObjects)
744 m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
746 HashSet<RenderBox*> oldIntrudingFloatSet;
747 if (!childrenInline() && m_floatingObjects) {
748 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
749 FloatingObjectSetIterator end = floatingObjectSet.end();
750 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
751 FloatingObject* floatingObject = *it;
752 if (!floatingObject->isDescendant())
753 oldIntrudingFloatSet.add(floatingObject->renderer());
757 // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
758 if (avoidsOrIgnoresFloats() || isRenderView()) {
759 if (m_floatingObjects) {
760 m_floatingObjects->clear();
762 if (!oldIntrudingFloatSet.isEmpty())
763 markAllDescendantsWithFloatsForLayout();
767 RendererToFloatInfoMap floatMap;
769 if (m_floatingObjects) {
770 if (childrenInline())
771 m_floatingObjects->moveAllToFloatInfoMap(floatMap);
773 m_floatingObjects->clear();
776 // We should not process floats if the parent node is not a RenderBlockFlow. Otherwise, we will add
777 // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
778 // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
779 if (!parent() || !parent()->isRenderBlockFlow())
782 // Attempt to locate a previous sibling with overhanging floats. We skip any elements that
783 // may have shifted to avoid floats, and any objects whose floats cannot interact with objects
784 // outside it (i.e. objects that create a new block formatting context).
785 RenderBlockFlow* parentBlockFlow = toRenderBlockFlow(parent());
786 bool parentHasFloats = false;
787 RenderObject* prev = previousSibling();
788 while (prev && (!prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsOrIgnoresFloats())) {
789 if (prev->isFloating())
790 parentHasFloats = true;
791 prev = prev->previousSibling();
794 // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
795 // them (as opposed to floats they contain themselves) so check for those here too.
796 LayoutUnit logicalTopOffset = logicalTop();
797 bool parentHasIntrudingFloats = !parentHasFloats && (!prev || toRenderBlockFlow(prev)->isSelfCollapsingBlock()) && parentBlockFlow->lowestFloatLogicalBottom() > logicalTopOffset;
798 if (parentHasFloats || parentHasIntrudingFloats)
799 addIntrudingFloats(parentBlockFlow, parentBlockFlow->logicalLeftOffsetForContent(), logicalTopOffset);
801 // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
803 RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
804 logicalTopOffset -= blockFlow->logicalTop();
805 if (blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
806 addIntrudingFloats(blockFlow, 0, logicalTopOffset);
809 if (childrenInline()) {
810 LayoutUnit changeLogicalTop = LayoutUnit::max();
811 LayoutUnit changeLogicalBottom = LayoutUnit::min();
812 if (m_floatingObjects) {
813 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
814 FloatingObjectSetIterator end = floatingObjectSet.end();
815 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
816 FloatingObject* floatingObject = *it;
817 FloatingObject* oldFloatingObject = floatMap.get(floatingObject->renderer());
818 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
819 if (oldFloatingObject) {
820 LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
821 if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject)) {
822 changeLogicalTop = 0;
823 changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
825 if (logicalBottom != oldLogicalBottom) {
826 changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
827 changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
829 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
830 LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
831 if (logicalTop != oldLogicalTop) {
832 changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
833 changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
837 floatMap.remove(floatingObject->renderer());
838 if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
839 ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
840 oldFloatingObject->originatingLine()->markDirty();
842 delete oldFloatingObject;
844 changeLogicalTop = 0;
845 changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
850 RendererToFloatInfoMap::iterator end = floatMap.end();
851 for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
852 FloatingObject* floatingObject = (*it).value;
853 if (!floatingObject->isDescendant()) {
854 changeLogicalTop = 0;
855 changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
858 deleteAllValues(floatMap);
860 markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
861 } else if (!oldIntrudingFloatSet.isEmpty()) {
862 // If there are previously intruding floats that no longer intrude, then children with floats
863 // should also get layout because they might need their floating object lists cleared.
864 if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size()) {
865 markAllDescendantsWithFloatsForLayout();
867 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
868 FloatingObjectSetIterator end = floatingObjectSet.end();
869 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
870 oldIntrudingFloatSet.remove((*it)->renderer());
871 if (!oldIntrudingFloatSet.isEmpty())
872 markAllDescendantsWithFloatsForLayout();
877 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, SubtreeLayoutScope& layoutScope, LayoutUnit beforeEdge, LayoutUnit afterEdge)
879 dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
881 // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
882 MarginInfo marginInfo(this, beforeEdge, afterEdge);
884 // Fieldsets need to find their legend and position it inside the border of the object.
885 // The legend then gets skipped during normal layout. The same is true for ruby text.
886 // It doesn't get included in the normal layout process but is instead skipped.
887 RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
889 LayoutUnit previousFloatLogicalBottom = 0;
891 RenderBox* next = firstChildBox();
892 RenderBox* lastNormalFlowChild = 0;
895 RenderBox* child = next;
896 next = child->nextSiblingBox();
898 // FIXME: this should only be set from clearNeedsLayout crbug.com/361250
899 child->setLayoutDidGetCalled(true);
901 if (childToExclude == child)
902 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
904 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
906 if (child->isOutOfFlowPositioned()) {
907 child->containingBlock()->insertPositionedObject(child);
908 adjustPositionedBlock(child, marginInfo);
911 if (child->isFloating()) {
912 insertFloatingObject(child);
913 adjustFloatingBlock(marginInfo);
917 // Lay out the child.
918 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom);
919 lastNormalFlowChild = child;
922 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
923 // determining the correct collapsed bottom margin information.
924 handleAfterSideOfBlock(lastNormalFlowChild, beforeEdge, afterEdge, marginInfo);
927 // Our MarginInfo state used when laying out block children.
928 MarginInfo::MarginInfo(RenderBlockFlow* blockFlow, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
929 : m_canCollapseMarginAfterWithLastChild(true)
930 , m_atBeforeSideOfBlock(true)
931 , m_atAfterSideOfBlock(false)
932 , m_hasMarginBeforeQuirk(false)
933 , m_hasMarginAfterQuirk(false)
934 , m_determinedMarginBeforeQuirk(false)
935 , m_discardMargin(false)
937 RenderStyle* blockStyle = blockFlow->style();
938 ASSERT(blockFlow->isRenderView() || blockFlow->parent());
939 m_canCollapseWithChildren = !blockFlow->createsBlockFormattingContext() && !blockFlow->isRenderFlowThread() && !blockFlow->isRenderView();
941 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
943 // If any height other than auto is specified in CSS, then we don't collapse our bottom
944 // margins with our children's margins. To do otherwise would be to risk odd visual
945 // effects when the children overflow out of the parent block and yet still collapse
946 // with it. We also don't collapse if we have any bottom border/padding.
947 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
948 && (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
950 m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody();
952 m_discardMargin = m_canCollapseMarginBeforeWithChildren && blockFlow->mustDiscardMarginBefore();
954 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxPositiveMarginBefore() : LayoutUnit();
955 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxNegativeMarginBefore() : LayoutUnit();
958 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox* child) const
960 LayoutUnit childBeforePositive = 0;
961 LayoutUnit childBeforeNegative = 0;
962 LayoutUnit childAfterPositive = 0;
963 LayoutUnit childAfterNegative = 0;
965 LayoutUnit beforeMargin = 0;
966 LayoutUnit afterMargin = 0;
968 RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
970 // If the child has the same directionality as we do, then we can just return its
971 // margins in the same direction.
972 if (!child->isWritingModeRoot()) {
973 if (childRenderBlockFlow) {
974 childBeforePositive = childRenderBlockFlow->maxPositiveMarginBefore();
975 childBeforeNegative = childRenderBlockFlow->maxNegativeMarginBefore();
976 childAfterPositive = childRenderBlockFlow->maxPositiveMarginAfter();
977 childAfterNegative = childRenderBlockFlow->maxNegativeMarginAfter();
979 beforeMargin = child->marginBefore();
980 afterMargin = child->marginAfter();
982 } else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
983 // The child has a different directionality. If the child is parallel, then it's just
984 // flipped relative to us. We can use the margins for the opposite edges.
985 if (childRenderBlockFlow) {
986 childBeforePositive = childRenderBlockFlow->maxPositiveMarginAfter();
987 childBeforeNegative = childRenderBlockFlow->maxNegativeMarginAfter();
988 childAfterPositive = childRenderBlockFlow->maxPositiveMarginBefore();
989 childAfterNegative = childRenderBlockFlow->maxNegativeMarginBefore();
991 beforeMargin = child->marginAfter();
992 afterMargin = child->marginBefore();
995 // The child is perpendicular to us, which means its margins don't collapse but are on the
996 // "logical left/right" sides of the child box. We can just return the raw margin in this case.
997 beforeMargin = marginBeforeForChild(child);
998 afterMargin = marginAfterForChild(child);
1001 // Resolve uncollapsing margins into their positive/negative buckets.
1003 if (beforeMargin > 0)
1004 childBeforePositive = beforeMargin;
1006 childBeforeNegative = -beforeMargin;
1009 if (afterMargin > 0)
1010 childAfterPositive = afterMargin;
1012 childAfterNegative = -afterMargin;
1015 return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
1018 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo, bool childIsSelfCollapsing)
1020 bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
1021 bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
1023 // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
1024 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
1026 // Get the four margin values for the child and cache them.
1027 const RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1029 // Get our max pos and neg top margins.
1030 LayoutUnit posTop = childMargins.positiveMarginBefore();
1031 LayoutUnit negTop = childMargins.negativeMarginBefore();
1033 // For self-collapsing blocks, collapse our bottom margins into our
1034 // top to get new posTop and negTop values.
1035 if (childIsSelfCollapsing) {
1036 posTop = max(posTop, childMargins.positiveMarginAfter());
1037 negTop = max(negTop, childMargins.negativeMarginAfter());
1040 // See if the top margin is quirky. We only care if this child has
1041 // margins that will collapse with us.
1042 bool topQuirk = hasMarginBeforeQuirk(child);
1044 if (marginInfo.canCollapseWithMarginBefore()) {
1045 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1046 // This child is collapsing with the top of the
1047 // block. If it has larger margin values, then we need to update
1048 // our own maximal values.
1049 if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
1050 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
1052 // The minute any of the margins involved isn't a quirk, don't
1053 // collapse it away, even if the margin is smaller (www.webreference.com
1054 // has an example of this, a <dt> with 0.8em author-specified inside
1055 // a <dl> inside a <td>.
1056 if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
1057 setHasMarginBeforeQuirk(false);
1058 marginInfo.setDeterminedMarginBeforeQuirk(true);
1061 if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore()) {
1062 // We have no top margin and our top child has a quirky margin.
1063 // We will pick up this quirky margin and pass it through.
1064 // This deals with the <td><div><p> case.
1065 // Don't do this for a block that split two inlines though. You do
1066 // still apply margins in this case.
1067 setHasMarginBeforeQuirk(true);
1070 // The before margin of the container will also discard all the margins it is collapsing with.
1071 setMustDiscardMarginBefore();
1075 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
1076 if (childDiscardMarginBefore) {
1077 marginInfo.setDiscardMargin(true);
1078 marginInfo.clearMargin();
1081 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1082 marginInfo.setHasMarginBeforeQuirk(topQuirk);
1084 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1085 LayoutUnit logicalTop = beforeCollapseLogicalTop;
1087 LayoutUnit clearanceForSelfCollapsingBlock;
1088 RenderObject* prev = child->previousSibling();
1089 RenderBlockFlow* previousBlockFlow = prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned() ? toRenderBlockFlow(prev) : 0;
1090 // 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
1091 // 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
1092 // 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.
1093 if (!marginInfo.canCollapseWithMarginBefore() && previousBlockFlow && previousBlockFlow->isSelfCollapsingBlock()) {
1094 clearanceForSelfCollapsingBlock = previousBlockFlow->marginOffsetForSelfCollapsingBlock();
1095 setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
1098 if (childIsSelfCollapsing) {
1099 // 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.
1100 // Also, the child's top position equals the logical height of the container.
1101 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1102 // This child has no height. We need to compute our
1103 // position before we collapse the child's margins together,
1104 // so that we can get an accurate position for the zero-height block.
1105 LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1106 LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1107 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1109 // Now collapse the child's margins together, which means examining our
1110 // bottom margin values as well.
1111 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1112 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1114 if (!marginInfo.canCollapseWithMarginBefore()) {
1115 // We need to make sure that the position of the self-collapsing block
1116 // is correct, since it could have overflowing content
1117 // that needs to be positioned correctly (e.g., a block that
1118 // had a specified height of 0 but that actually had subcontent).
1119 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1123 if (mustSeparateMarginBeforeForChild(child)) {
1124 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
1125 // If we are at the before side of the block and we collapse, ignore the computed margin
1126 // and just add the child margin to the container height. This will correctly position
1127 // the child inside the container.
1128 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
1129 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
1130 logicalTop = logicalHeight();
1131 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
1132 || (!marginInfo.canCollapseMarginBeforeWithChildren()
1133 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
1134 // We're collapsing with a previous sibling's margins and not
1135 // with the top of the block.
1136 setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
1137 logicalTop = logicalHeight();
1140 marginInfo.setDiscardMargin(childDiscardMarginAfter);
1142 if (!marginInfo.discardMargin()) {
1143 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1144 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1146 marginInfo.clearMargin();
1149 if (marginInfo.margin())
1150 marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
1153 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1154 // collapsed into the page edge.
1155 LayoutState* layoutState = view()->layoutState();
1156 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop) {
1157 LayoutUnit oldLogicalTop = logicalTop;
1158 logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1159 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1162 if (previousBlockFlow) {
1163 // 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
1164 // any floats from the parent will now overhang.
1165 LayoutUnit oldLogicalHeight = logicalHeight();
1166 setLogicalHeight(logicalTop);
1167 if (!previousBlockFlow->avoidsFloats() && (previousBlockFlow->logicalTop() + previousBlockFlow->lowestFloatLogicalBottom()) > logicalTop)
1168 addOverhangingFloats(previousBlockFlow, false);
1169 setLogicalHeight(oldLogicalHeight);
1171 // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
1172 // 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
1173 // floats in the parent that overhang |child|'s new logical top.
1174 bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
1175 if (logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1176 child->setNeedsLayout();
1182 void RenderBlockFlow::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1184 bool isHorizontal = isHorizontalWritingMode();
1185 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1187 LayoutUnit logicalTop = logicalHeight();
1188 updateStaticInlinePositionForChild(child, logicalTop);
1190 if (!marginInfo.canCollapseWithMarginBefore()) {
1191 // Positioned blocks don't collapse margins, so add the margin provided by
1192 // the container now. The child's own margin is added later when calculating its logical top.
1193 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1194 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1195 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1198 RenderLayer* childLayer = child->layer();
1199 if (childLayer->staticBlockPosition() != logicalTop) {
1200 childLayer->setStaticBlockPosition(logicalTop);
1201 if (hasStaticBlockPosition)
1202 child->setChildNeedsLayout(MarkOnlyThis);
1206 LayoutUnit RenderBlockFlow::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart)
1208 LayoutUnit startPosition = startOffsetForContent();
1210 // Add in our start margin.
1211 LayoutUnit oldPosition = startPosition + childMarginStart;
1212 LayoutUnit newPosition = oldPosition;
1214 LayoutUnit blockOffset = logicalTopForChild(child);
1215 LayoutUnit startOff = startOffsetForLine(blockOffset, false, logicalHeightForChild(child));
1217 if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
1218 if (childMarginStart < 0)
1219 startOff += childMarginStart;
1220 newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
1221 } else if (startOff != startPosition) {
1222 newPosition = startOff + childMarginStart;
1225 return newPosition - oldPosition;
1228 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing)
1230 LayoutUnit heightIncrease = getClearDelta(child, yPos);
1231 if (!heightIncrease)
1234 if (childIsSelfCollapsing) {
1235 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1237 // For self-collapsing blocks that clear, they can still collapse their
1238 // margins with following siblings. Reset the current margins to represent
1239 // the self-collapsing block's margins only.
1240 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
1241 RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1242 if (!childDiscardMargin) {
1243 marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1244 marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1246 marginInfo.clearMargin();
1248 marginInfo.setDiscardMargin(childDiscardMargin);
1251 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
1252 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
1253 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Set a bit to ensure
1254 // this happens; it will get reset if we encounter an in-flow sibling that is not self-collapsing.
1255 marginInfo.setCanCollapseMarginAfterWithLastChild(false);
1257 // 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
1258 // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
1259 // 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
1260 // margins can collapse at the correct vertical position.
1261 // 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
1262 // (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],
1263 // i.e., clearance = [height of float] - margin-top".
1264 setLogicalHeight(child->logicalTop() + childMargins.negativeMarginBefore());
1266 // Increase our height by the amount we had to clear.
1267 setLogicalHeight(logicalHeight() + heightIncrease);
1270 if (marginInfo.canCollapseWithMarginBefore()) {
1271 // We can no longer collapse with the top of the block since a clear
1272 // occurred. The empty blocks collapse into the cleared block.
1273 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1274 marginInfo.setAtBeforeSideOfBlock(false);
1276 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1277 setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
1280 return yPos + heightIncrease;
1283 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1285 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1286 // 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.
1287 // Don't update the max margin values because we won't need them anyway.
1288 if (marginInfo.discardMargin()) {
1289 setMustDiscardMarginAfter();
1293 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1294 // with our children.
1295 setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1297 if (!marginInfo.hasMarginAfterQuirk())
1298 setHasMarginAfterQuirk(false);
1300 if (marginInfo.hasMarginAfterQuirk() && !marginAfter()) {
1301 // We have no bottom margin and our last child has a quirky margin.
1302 // We will pick up this quirky margin and pass it through.
1303 // This deals with the <td><div><p> case.
1304 setHasMarginAfterQuirk(true);
1309 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1311 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1312 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1313 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1314 if ((document().inQuirksMode() && hasMarginBeforeQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
1317 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1318 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1319 if (child->style()->marginBeforeCollapse() == MDISCARD) {
1320 positiveMarginBefore = 0;
1321 negativeMarginBefore = 0;
1322 discardMarginBefore = true;
1326 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1327 positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
1328 negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
1330 if (!child->isRenderBlockFlow())
1333 RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1334 if (childBlockFlow->childrenInline() || childBlockFlow->isWritingModeRoot())
1337 MarginInfo childMarginInfo(childBlockFlow, childBlockFlow->borderBefore() + childBlockFlow->paddingBefore(), childBlockFlow->borderAfter() + childBlockFlow->paddingAfter());
1338 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1341 RenderBox* grandchildBox = childBlockFlow->firstChildBox();
1342 for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1343 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1347 // Give up if there is clearance on the box, since it probably won't collapse into us.
1348 if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
1351 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1352 if (grandchildBox->needsLayout()) {
1353 grandchildBox->computeAndSetBlockDirectionMargins(this);
1354 if (grandchildBox->isRenderBlock()) {
1355 RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
1356 grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
1357 grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
1361 // Collapse the margin of the grandchild box with our own to produce an estimate.
1362 childBlockFlow->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1365 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1367 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1368 // relayout if there are intruding floats.
1369 LayoutUnit logicalTopEstimate = logicalHeight();
1370 if (!marginInfo.canCollapseWithMarginBefore()) {
1371 LayoutUnit positiveMarginBefore = 0;
1372 LayoutUnit negativeMarginBefore = 0;
1373 bool discardMarginBefore = false;
1374 if (child->selfNeedsLayout()) {
1375 // Try to do a basic estimation of how the collapse is going to go.
1376 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1378 // Use the cached collapsed margin values from a previous layout. Most of the time they
1380 RenderBlockFlow::MarginValues marginValues = marginValuesForChild(child);
1381 positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
1382 negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
1383 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1386 // Collapse the result with our current margins.
1387 if (!discardMarginBefore)
1388 logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
1391 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1393 LayoutState* layoutState = view()->layoutState();
1394 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight())
1395 logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1397 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1399 estimateWithoutPagination = logicalTopEstimate;
1401 if (layoutState->isPaginated()) {
1402 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1403 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1405 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1406 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1408 if (!child->selfNeedsLayout() && child->isRenderBlock())
1409 logicalTopEstimate += toRenderBlock(child)->paginationStrut();
1412 return logicalTopEstimate;
1415 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
1417 ASSERT(isSelfCollapsingBlock());
1418 RenderBlockFlow* parentBlock = toRenderBlockFlow(parent());
1419 if (parentBlock && style()->clear() && parentBlock->getClearDelta(this, logicalHeight()))
1420 return marginValuesForChild(this).positiveMarginBefore();
1421 return LayoutUnit();
1424 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
1426 // The float should be positioned taking into account the bottom margin
1427 // of the previous flow. We add that margin into the height, get the
1428 // float positioned properly, and then subtract the margin out of the
1429 // height again. In the case of self-collapsing blocks, we always just
1430 // use the top margins, since the self-collapsing block collapsed its
1431 // own bottom margin into its top margin.
1433 // Note also that the previous flow may collapse its margin into the top of
1434 // our block. If this is the case, then we do not add the margin in to our
1435 // height when computing the position of the float. This condition can be tested
1436 // for by simply calling canCollapseWithMarginBefore. See
1437 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1438 // an example of this scenario.
1439 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1440 setLogicalHeight(logicalHeight() + marginOffset);
1441 positionNewFloats();
1442 setLogicalHeight(logicalHeight() - marginOffset);
1445 void RenderBlockFlow::handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1447 marginInfo.setAtAfterSideOfBlock(true);
1449 // If our last child was a self-collapsing block with clearance then our logical height is flush with the
1450 // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
1451 // to perform now is at the child's margin-top - so adjust our height to that position.
1452 if (lastChild && lastChild->isRenderBlockFlow() && lastChild->isSelfCollapsingBlock())
1453 setLogicalHeight(logicalHeight() - toRenderBlockFlow(lastChild)->marginOffsetForSelfCollapsingBlock());
1455 if (marginInfo.canCollapseMarginAfterWithChildren() && !marginInfo.canCollapseMarginAfterWithLastChild())
1456 marginInfo.setCanCollapseMarginAfterWithChildren(false);
1458 // If we can't collapse with children then go ahead and add in the bottom margin.
1459 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1460 && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1461 setLogicalHeight(logicalHeight() + marginInfo.margin());
1463 // Now add in our bottom border/padding.
1464 setLogicalHeight(logicalHeight() + afterSide);
1466 // Negative margins can cause our height to shrink below our minimal height (border/padding).
1467 // If this happens, ensure that the computed height is increased to the minimal height.
1468 setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
1470 // Update our bottom collapsed margin info.
1471 setCollapsedBottomMargin(marginInfo);
1474 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1476 if (style()->marginBeforeCollapse() == MDISCARD) {
1481 if (!m_rareData && !value)
1485 m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1487 m_rareData->m_discardMarginBefore = value;
1490 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1492 if (style()->marginAfterCollapse() == MDISCARD) {
1497 if (!m_rareData && !value)
1501 m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1503 m_rareData->m_discardMarginAfter = value;
1506 bool RenderBlockFlow::mustDiscardMarginBefore() const
1508 return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
1511 bool RenderBlockFlow::mustDiscardMarginAfter() const
1513 return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
1516 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox* child) const
1518 ASSERT(!child->selfNeedsLayout());
1519 if (!child->isWritingModeRoot())
1520 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1521 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1522 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1524 // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1525 // In case the boxes are perpendicular we assume the property is not specified.
1529 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox* child) const
1531 ASSERT(!child->selfNeedsLayout());
1532 if (!child->isWritingModeRoot())
1533 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1534 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1535 return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1537 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1541 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1544 if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(this))
1546 m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1548 m_rareData->m_margins.setPositiveMarginBefore(pos);
1549 m_rareData->m_margins.setNegativeMarginBefore(neg);
1552 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1555 if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(this))
1557 m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1559 m_rareData->m_margins.setPositiveMarginAfter(pos);
1560 m_rareData->m_margins.setNegativeMarginAfter(neg);
1563 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox* child) const
1565 ASSERT(!child->selfNeedsLayout());
1566 const RenderStyle* childStyle = child->style();
1567 if (!child->isWritingModeRoot())
1568 return childStyle->marginBeforeCollapse() == MSEPARATE;
1569 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1570 return childStyle->marginAfterCollapse() == MSEPARATE;
1572 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1576 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox* child) const
1578 ASSERT(!child->selfNeedsLayout());
1579 const RenderStyle* childStyle = child->style();
1580 if (!child->isWritingModeRoot())
1581 return childStyle->marginAfterCollapse() == MSEPARATE;
1582 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1583 return childStyle->marginBeforeCollapse() == MSEPARATE;
1585 // FIXME: See |mustDiscardMarginBeforeForChild| above.
1589 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
1591 // FIXME: Add page break checking here when we support printing.
1592 RenderFlowThread* flowThread = flowThreadContainingBlock();
1593 bool isInsideMulticolFlowThread = flowThread;
1594 bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1595 bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1596 bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS)
1597 || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS);
1598 if (checkBeforeAlways && inNormalFlow(child)) {
1599 if (checkColumnBreaks) {
1600 if (isInsideMulticolFlowThread) {
1601 LayoutUnit offsetBreakAdjustment = 0;
1602 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
1603 return logicalOffset + offsetBreakAdjustment;
1605 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1608 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1610 return logicalOffset;
1613 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1615 // FIXME: Add page break checking here when we support printing.
1616 RenderFlowThread* flowThread = flowThreadContainingBlock();
1617 bool isInsideMulticolFlowThread = flowThread;
1618 bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1619 bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->pageLogicalHeight(); // FIXME: Once columns can print we have to check this.
1620 bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS)
1621 || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS);
1622 if (checkAfterAlways && inNormalFlow(child)) {
1623 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1625 // So our margin doesn't participate in the next collapsing steps.
1626 marginInfo.clearMargin();
1628 if (checkColumnBreaks) {
1629 if (isInsideMulticolFlowThread) {
1630 LayoutUnit offsetBreakAdjustment = 0;
1631 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
1632 return logicalOffset + marginOffset + offsetBreakAdjustment;
1634 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1637 return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1639 return logicalOffset;
1642 void RenderBlockFlow::addOverflowFromFloats()
1644 if (!m_floatingObjects)
1647 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1648 FloatingObjectSetIterator end = floatingObjectSet.end();
1649 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1650 FloatingObject* floatingObject = *it;
1651 if (floatingObject->isDescendant())
1652 addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
1656 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1658 RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
1659 if (!hasColumns() && (recomputeFloats || createsBlockFormattingContext() || hasSelfPaintingLayer()))
1660 addOverflowFromFloats();
1663 RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
1665 RootInlineBox* rootBox = createRootInlineBox();
1666 m_lineBoxes.appendLineBox(rootBox);
1668 if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1669 if (AXObjectCache* cache = document().existingAXObjectCache())
1670 cache->recomputeIsIgnored(this);
1676 void RenderBlockFlow::deleteLineBoxTree()
1678 if (containsFloats())
1679 m_floatingObjects->clearLineBoxTreePointers();
1680 RenderBlock::deleteLineBoxTree();
1683 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
1685 if (!everHadLayout() && !containsFloats())
1688 MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
1689 setChildNeedsLayout(markParents);
1692 removeFloatingObject(floatToRemove);
1694 // Iterate over our children and mark them as needed.
1695 if (!childrenInline()) {
1696 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1697 if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
1699 if (!child->isRenderBlockFlow()) {
1700 RenderBlock* childBlock = toRenderBlock(child);
1701 if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
1702 childBlock->setChildNeedsLayout(markParents);
1705 RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1706 if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
1707 childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
1712 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
1714 if (!m_floatingObjects)
1717 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1718 FloatingObjectSetIterator end = floatingObjectSet.end();
1720 for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
1721 if (!next->isRenderBlockFlow() || avoidsOrIgnoresFloats())
1724 RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1725 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1726 RenderBox* floatingBox = (*it)->renderer();
1727 if (floatToRemove && floatingBox != floatToRemove)
1729 if (nextBlock->containsFloat(floatingBox))
1730 nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
1735 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
1737 // There is no need to compute clearance if we have no floats.
1738 if (!containsFloats())
1741 // At least one float is present. We need to perform the clearance computation.
1742 bool clearSet = child->style()->clear() != CNONE;
1743 LayoutUnit logicalBottom = 0;
1744 switch (child->style()->clear()) {
1748 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
1751 logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
1754 logicalBottom = lowestFloatLogicalBottom();
1758 // 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).
1759 LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
1760 if (!result && child->avoidsFloats()) {
1761 LayoutUnit newLogicalTop = logicalTop;
1763 LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
1764 if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent())
1765 return newLogicalTop - logicalTop;
1767 LayoutRect borderBox = child->borderBoxRect();
1768 LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1770 // FIXME: None of this is right for perpendicular writing-mode children.
1771 LayoutUnit childOldLogicalWidth = child->logicalWidth();
1772 LayoutUnit childOldMarginLeft = child->marginLeft();
1773 LayoutUnit childOldMarginRight = child->marginRight();
1774 LayoutUnit childOldLogicalTop = child->logicalTop();
1776 child->setLogicalTop(newLogicalTop);
1777 child->updateLogicalWidth();
1778 borderBox = child->borderBoxRect();
1779 LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1781 child->setLogicalTop(childOldLogicalTop);
1782 child->setLogicalWidth(childOldLogicalWidth);
1783 child->setMarginLeft(childOldMarginLeft);
1784 child->setMarginRight(childOldMarginRight);
1786 if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
1787 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
1788 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
1789 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
1790 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
1791 child->setChildNeedsLayout(MarkOnlyThis);
1792 return newLogicalTop - logicalTop;
1795 newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
1796 ASSERT(newLogicalTop >= logicalTop);
1797 if (newLogicalTop < logicalTop)
1800 ASSERT_NOT_REACHED();
1805 void RenderBlockFlow::createFloatingObjects()
1807 m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
1810 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
1812 RenderStyle* oldStyle = style();
1813 s_canPropagateFloatIntoSibling = oldStyle ? !createsBlockFormattingContext() : false;
1814 if (oldStyle && parent() && diff.needsFullLayout() && oldStyle->position() != newStyle.position()
1815 && containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
1816 markAllDescendantsWithFloatsForLayout();
1818 RenderBlock::styleWillChange(diff, newStyle);
1821 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1823 RenderBlock::styleDidChange(diff, oldStyle);
1825 // After our style changed, if we lose our ability to propagate floats into next sibling
1826 // blocks, then we need to find the top most parent containing that overhanging float and
1827 // then mark its descendants with floats for layout and clear all floats from its next
1828 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
1829 bool canPropagateFloatIntoSibling = !createsBlockFormattingContext();
1830 if (diff.needsFullLayout() && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
1831 RenderBlockFlow* parentBlockFlow = this;
1832 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1833 FloatingObjectSetIterator end = floatingObjectSet.end();
1835 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
1836 if (curr->isRenderBlockFlow()) {
1837 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
1839 if (currBlock->hasOverhangingFloats()) {
1840 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1841 RenderBox* renderer = (*it)->renderer();
1842 if (currBlock->hasOverhangingFloat(renderer)) {
1843 parentBlockFlow = currBlock;
1851 parentBlockFlow->markAllDescendantsWithFloatsForLayout();
1852 parentBlockFlow->markSiblingsWithFloatsForLayout();
1855 if (diff.needsFullLayout() || !oldStyle)
1856 createOrDestroyMultiColumnFlowThreadIfNeeded();
1859 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
1861 if (child->style()->isOriginalDisplayInlineType())
1862 setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
1864 setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent());
1867 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
1869 child->layer()->setStaticInlinePosition(inlinePosition);
1872 void RenderBlockFlow::addChild(RenderObject* newChild, RenderObject* beforeChild)
1874 if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread())
1875 return flowThread->addChild(newChild, beforeChild);
1876 RenderBlock::addChild(newChild, beforeChild);
1879 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1881 RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
1882 moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
1884 // When a portion of the render tree is being detached, anonymous blocks
1885 // will be combined as their children are deleted. In this process, the
1886 // anonymous block later in the tree is merged into the one preceeding it.
1887 // It can happen that the later block (this) contains floats that the
1888 // previous block (toBlockFlow) did not contain, and thus are not in the
1889 // floating objects list for toBlockFlow. This can result in toBlockFlow containing
1890 // floats that are not in it's floating objects list, but are in the
1891 // floating objects lists of siblings and parents. This can cause problems
1892 // when the float itself is deleted, since the deletion code assumes that
1893 // if a float is not in it's containing block's floating objects list, it
1894 // isn't in any floating objects list. In order to preserve this condition
1895 // (removing it has serious performance implications), we need to copy the
1896 // floating objects from the old block (this) to the new block (toBlockFlow).
1897 // The float's metrics will likely all be wrong, but since toBlockFlow is
1898 // already marked for layout, this will get fixed before anything gets
1900 // See bug https://code.google.com/p/chromium/issues/detail?id=230907
1901 if (m_floatingObjects) {
1902 if (!toBlockFlow->m_floatingObjects)
1903 toBlockFlow->createFloatingObjects();
1905 const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1906 FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1908 for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1909 FloatingObject* floatingObject = *it;
1911 // Don't insert the object again if it's already in the list
1912 if (toBlockFlow->containsFloat(floatingObject->renderer()))
1915 toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
1921 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
1923 // Repaint any overhanging floats (if we know we're the one to paint them).
1924 // Otherwise, bail out.
1925 if (!hasOverhangingFloats())
1928 // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
1929 // in this block. Better yet would be to push extra state for the containers of other floats.
1930 LayoutStateDisabler layoutStateDisabler(*this);
1931 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1932 FloatingObjectSetIterator end = floatingObjectSet.end();
1933 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1934 FloatingObject* floatingObject = *it;
1935 // Only repaint the object if it is overhanging, is not in its own layer, and
1936 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
1937 // condition is replaced with being a descendant of us.
1938 if (logicalBottomForFloat(floatingObject) > logicalHeight()
1939 && !floatingObject->renderer()->hasSelfPaintingLayer()
1940 && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer()->isDescendantOf(this)))) {
1942 RenderBox* floatingRenderer = floatingObject->renderer();
1943 if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
1944 floatingRenderer->setShouldDoFullRepaintAfterLayout(true);
1946 floatingRenderer->repaint();
1948 floatingRenderer->repaintOverhangingFloats(false);
1953 void RenderBlockFlow::repaintOverflow()
1955 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1956 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
1957 LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1958 LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1959 if (hasOverflowClip()) {
1960 // 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.
1961 // 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.
1962 // layoutInlineChildren should be patched to compute the entire repaint rect.
1963 repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1964 repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1967 LayoutRect repaintRect;
1968 if (isHorizontalWritingMode())
1969 repaintRect = LayoutRect(repaintLogicalLeft, m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop);
1971 repaintRect = LayoutRect(m_repaintLogicalTop, repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1973 // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1974 adjustRectForColumns(repaintRect);
1976 if (hasOverflowClip()) {
1977 // Adjust repaint rect for scroll offset
1978 repaintRect.move(-scrolledContentOffset());
1980 // Don't allow this rect to spill out of our overflow box.
1981 repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1984 // Make sure the rect is still non-empty after intersecting for overflow above
1985 if (!repaintRect.isEmpty()) {
1986 // Hits in media/event-attributes.html
1987 DisableCompositingQueryAsserts disabler;
1989 repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1990 if (hasReflection())
1991 repaintRectangle(reflectedRect(repaintRect));
1994 m_repaintLogicalTop = 0;
1995 m_repaintLogicalBottom = 0;
1998 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
2000 if (!m_floatingObjects)
2003 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2004 FloatingObjectSetIterator end = floatingObjectSet.end();
2005 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2006 FloatingObject* floatingObject = *it;
2007 // Only paint the object if our m_shouldPaint flag is set.
2008 if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
2009 PaintInfo currentPaintInfo(paintInfo);
2010 currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
2011 // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
2012 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y()));
2013 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
2014 if (!preservePhase) {
2015 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
2016 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
2017 currentPaintInfo.phase = PaintPhaseFloat;
2018 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
2019 currentPaintInfo.phase = PaintPhaseForeground;
2020 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
2021 currentPaintInfo.phase = PaintPhaseOutline;
2022 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
2028 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
2030 if (m_floatingObjects) {
2031 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2032 FloatingObjectSetIterator end = floatingObjectSet.end();
2033 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2034 FloatingObject* floatingObject = *it;
2035 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
2036 offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
2037 floatingObject->renderer()->width(), floatingObject->renderer()->height());
2038 rootBlock->flipForWritingMode(floatBox);
2039 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
2040 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
2045 void RenderBlockFlow::clearFloats(EClear clear)
2047 positionNewFloats();
2049 LayoutUnit newY = 0;
2052 newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2055 newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2058 newY = lowestFloatLogicalBottom();
2062 if (height() < newY)
2063 setLogicalHeight(newY);
2066 bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
2068 return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
2071 void RenderBlockFlow::removeFloatingObjects()
2073 if (!m_floatingObjects)
2076 markSiblingsWithFloatsForLayout();
2078 m_floatingObjects->clear();
2081 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2083 if (!style()->isFlippedBlocksWritingMode())
2086 // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2087 // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2089 if (isHorizontalWritingMode())
2090 return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
2091 return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2094 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2096 LayoutUnit offset = fixedOffset;
2097 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2098 offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2099 return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2102 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2104 LayoutUnit offset = fixedOffset;
2105 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2106 offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2107 return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2110 LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2112 LayoutUnit left = offsetFromFloats;
2114 if (applyTextIndent && style()->isLeftToRightDirection())
2115 left += textIndentOffset();
2120 LayoutUnit RenderBlockFlow::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2122 LayoutUnit right = offsetFromFloats;
2124 if (applyTextIndent && !style()->isLeftToRightDirection())
2125 right -= textIndentOffset();
2130 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
2132 RenderBox* childBox = floatingObject->renderer();
2133 LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2134 LayoutUnit logicalRightOffset; // Constant part of right offset.
2135 logicalRightOffset = logicalRightOffsetForContent();
2137 LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2139 LayoutUnit floatLogicalLeft;
2141 bool insideFlowThread = flowThreadContainingBlock();
2143 if (childBox->style()->floating() == LeftFloat) {
2144 LayoutUnit heightRemainingLeft = 1;
2145 LayoutUnit heightRemainingRight = 1;
2146 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2147 while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2148 logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
2149 floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2150 if (insideFlowThread) {
2151 // Have to re-evaluate all of our offsets, since they may have changed.
2152 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2153 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2154 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2157 floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2159 LayoutUnit heightRemainingLeft = 1;
2160 LayoutUnit heightRemainingRight = 1;
2161 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2162 while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2163 logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
2164 floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2165 if (insideFlowThread) {
2166 // Have to re-evaluate all of our offsets, since they may have changed.
2167 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2168 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2169 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2172 // Use the original width of the float here, since the local variable
2173 // |floatLogicalWidth| was capped to the available line width. See
2174 // fast/block/float/clamped-right-float.html.
2175 floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2178 return LayoutPoint(floatLogicalLeft, logicalTopOffset);
2181 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
2183 ASSERT(floatBox->isFloating());
2185 // Create the list of special objects if we don't aleady have one
2186 if (!m_floatingObjects) {
2187 createFloatingObjects();
2189 // Don't insert the object again if it's already in the list
2190 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2191 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2192 if (it != floatingObjectSet.end())
2196 // Create the special object entry & append it to the list
2198 OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
2200 // Our location is irrelevant if we're unsplittable or no pagination is in effect.
2201 // Just go ahead and lay out the float.
2202 bool isChildRenderBlock = floatBox->isRenderBlock();
2203 if (isChildRenderBlock && !floatBox->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
2204 floatBox->setChildNeedsLayout(MarkOnlyThis);
2206 bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2207 if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
2208 floatBox->layoutIfNeeded();
2210 floatBox->updateLogicalWidth();
2211 floatBox->computeAndSetBlockDirectionMargins(this);
2214 setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2216 return m_floatingObjects->add(newObj.release());
2219 void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
2221 if (m_floatingObjects) {
2222 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2223 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2224 if (it != floatingObjectSet.end()) {
2225 FloatingObject* floatingObject = *it;
2226 if (childrenInline()) {
2227 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
2228 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
2230 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
2231 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max()) {
2232 logicalBottom = LayoutUnit::max();
2234 // Special-case zero- and less-than-zero-height floats: those don't touch
2235 // the line that they're on, but it still needs to be dirtied. This is
2236 // accomplished by pretending they have a height of 1.
2237 logicalBottom = max(logicalBottom, logicalTop + 1);
2239 if (floatingObject->originatingLine()) {
2240 if (!selfNeedsLayout()) {
2241 ASSERT(floatingObject->originatingLine()->renderer() == this);
2242 floatingObject->originatingLine()->markDirty();
2244 #if !ASSERT_DISABLED
2245 floatingObject->setOriginatingLine(0);
2248 markLinesDirtyInBlockRange(0, logicalBottom);
2250 m_floatingObjects->remove(floatingObject);
2255 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2257 if (!containsFloats())
2260 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2261 FloatingObject* curr = floatingObjectSet.last();
2262 while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
2263 m_floatingObjects->remove(curr);
2264 if (floatingObjectSet.isEmpty())
2266 curr = floatingObjectSet.last();
2270 bool RenderBlockFlow::positionNewFloats()
2272 if (!m_floatingObjects)
2275 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2276 if (floatingObjectSet.isEmpty())
2279 // If all floats have already been positioned, then we have no work to do.
2280 if (floatingObjectSet.last()->isPlaced())
2283 // Move backwards through our floating object list until we find a float that has
2284 // already been positioned. Then we'll be able to move forward, positioning all of
2285 // the new floats that need it.
2286 FloatingObjectSetIterator it = floatingObjectSet.end();
2287 --it; // Go to last item.
2288 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2289 FloatingObject* lastPlacedFloatingObject = 0;
2290 while (it != begin) {
2292 if ((*it)->isPlaced()) {
2293 lastPlacedFloatingObject = *it;
2299 LayoutUnit logicalTop = logicalHeight();
2301 // The float cannot start above the top position of the last positioned float.
2302 if (lastPlacedFloatingObject)
2303 logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
2305 FloatingObjectSetIterator end = floatingObjectSet.end();
2306 // Now walk through the set of unpositioned floats and place them.
2307 for (; it != end; ++it) {
2308 FloatingObject* floatingObject = *it;
2309 // The containing block is responsible for positioning floats, so if we have floats in our
2310 // list that come from somewhere else, do not attempt to position them.
2311 if (floatingObject->renderer()->containingBlock() != this)
2314 RenderBox* childBox = floatingObject->renderer();
2316 // FIXME Investigate if this can be removed. crbug.com/370006
2317 childBox->setMayNeedInvalidation(true);
2319 LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2320 LayoutRect oldRect = childBox->frameRect();
2322 if (childBox->style()->clear() & CLEFT)
2323 logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2324 if (childBox->style()->clear() & CRIGHT)
2325 logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2327 LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
2329 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2331 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2332 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2334 SubtreeLayoutScope layoutScope(*childBox);
2335 LayoutState* layoutState = view()->layoutState();
2336 bool isPaginated = layoutState->isPaginated();
2337 if (isPaginated && !childBox->needsLayout())
2338 childBox->markForPaginationRelayoutIfNeeded(layoutScope);
2340 childBox->layoutIfNeeded();
2343 // If we are unsplittable and don't fit, then we need to move down.
2344 // We include our margins as part of the unsplittable area.
2345 LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
2347 // See if we have a pagination strut that is making us move down further.
2348 // Note that an unsplittable child can't also have a pagination strut, so this is
2349 // exclusive with the case above.
2350 RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
2351 if (childBlock && childBlock->paginationStrut()) {
2352 newLogicalTop += childBlock->paginationStrut();
2353 childBlock->setPaginationStrut(0);
2356 if (newLogicalTop != floatLogicalLocation.y()) {
2357 floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
2359 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2360 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2362 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2363 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2366 childBlock->setChildNeedsLayout(MarkOnlyThis);
2367 childBox->layoutIfNeeded();
2371 setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
2373 setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2375 m_floatingObjects->addPlacedObject(floatingObject);
2377 if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
2378 shapeOutside->setReferenceBoxLogicalSize(logicalSizeForChild(childBox));
2380 // If the child moved, we have to repaint it.
2381 if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()
2382 && childBox->checkForRepaintDuringLayout())
2383 childBox->repaintDuringLayoutIfMoved(oldRect);
2388 bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
2390 if (!m_floatingObjects || hasColumns() || !parent())
2393 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2394 FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
2395 if (it == floatingObjectSet.end())
2398 return logicalBottomForFloat(*it) > logicalHeight();
2401 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2403 ASSERT(!avoidsFloats());
2405 // If we create our own block formatting context then our contents don't interact with floats outside it, even those from our parent.
2406 if (createsBlockFormattingContext())
2409 // If the parent or previous sibling doesn't have any floats to add, don't bother.
2410 if (!prev->m_floatingObjects)
2413 logicalLeftOffset += marginLogicalLeft();
2415 const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2416 FloatingObjectSetIterator prevEnd = prevSet.end();
2417 for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2418 FloatingObject* floatingObject = *prevIt;
2419 if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2420 if (!m_floatingObjects || !m_floatingObjects->set().contains(floatingObject)) {
2421 // We create the floating object list lazily.
2422 if (!m_floatingObjects)
2423 createFloatingObjects();
2425 // Applying the child's margin makes no sense in the case where the child was passed in.
2426 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2427 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2428 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2429 // will get applied twice.
2430 LayoutSize offset = isHorizontalWritingMode()
2431 ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2432 : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
2434 m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
2440 void RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
2442 // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2443 if (!child->containsFloats() || child->isRenderRegion() || child->createsBlockFormattingContext())
2446 LayoutUnit childLogicalTop = child->logicalTop();
2447 LayoutUnit childLogicalLeft = child->logicalLeft();
2449 // Floats that will remain the child's responsibility to paint should factor into its
2451 FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
2452 for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2453 FloatingObject* floatingObject = *childIt;
2454 LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2455 LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
2457 if (logicalBottom > logicalHeight()) {
2458 // If the object is not in the list, we add it now.
2459 if (!containsFloat(floatingObject->renderer())) {
2460 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2461 bool shouldPaint = false;
2463 // The nearest enclosing layer always paints the float (so that zindex and stacking
2464 // behaves properly). We always want to propagate the desire to paint the float as
2465 // far out as we can, to the outermost block that overlaps the float, stopping only
2466 // if we hit a self-painting layer boundary.
2467 if (floatingObject->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2468 floatingObject->setShouldPaint(false);
2471 // We create the floating object list lazily.
2472 if (!m_floatingObjects)
2473 createFloatingObjects();
2475 m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
2478 if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()
2479 && floatingObject->renderer()->isDescendantOf(child) && floatingObject->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
2480 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2481 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2483 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2485 floatingObject->setShouldPaint(true);
2488 // 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
2490 if (floatingObject->isDescendant())
2491 child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
2496 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2498 if (!m_floatingObjects)
2501 return m_floatingObjects->lowestFloatLogicalBottom(floatType);
2504 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
2506 if (!m_floatingObjects)
2507 return logicalHeight;
2509 LayoutUnit logicalBottom;
2510 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2511 FloatingObjectSetIterator end = floatingObjectSet.end();
2512 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2513 FloatingObject* floatingObject = *it;
2514 LayoutUnit floatLogicalBottom = logicalBottomForFloat(floatingObject);
2515 ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
2516 if (shapeOutside && (offsetMode == ShapeOutsideFloatShapeOffset)) {
2517 LayoutUnit shapeLogicalBottom = logicalTopForFloat(floatingObject) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
2518 // Use the shapeLogicalBottom unless it extends outside of the margin box, in which case it is clipped.
2519 if (shapeLogicalBottom < floatLogicalBottom)
2520 floatLogicalBottom = shapeLogicalBottom;
2522 if (floatLogicalBottom > logicalHeight)
2523 logicalBottom = logicalBottom ? min(floatLogicalBottom, logicalBottom) : floatLogicalBottom;
2526 return logicalBottom;
2529 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2531 if (!m_floatingObjects)
2534 LayoutPoint adjustedLocation = accumulatedOffset;
2535 if (isRenderView()) {
2536 adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
2539 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2540 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2541 for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
2543 FloatingObject* floatingObject = *it;
2544 if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
2545 LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
2546 LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
2547 LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
2548 if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
2549 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2558 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2560 RenderBlock::adjustForBorderFit(x, left, right);
2561 if (m_floatingObjects && style()->visibility() == VISIBLE) {
2562 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2563 FloatingObjectSetIterator end = floatingObjectSet.end();
2564 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2565 FloatingObject* floatingObject = *it;
2566 // Only examine the object if our m_shouldPaint flag is set.
2567 if (floatingObject->shouldPaint()) {
2568 LayoutUnit floatLeft = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
2569 LayoutUnit floatRight = floatLeft + floatingObject->renderer()->width();
2570 left = min(left, floatLeft);
2571 right = max(right, floatRight);
2577 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2579 if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2580 return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2585 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2587 if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2588 return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2593 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2594 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2598 bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2600 if (!firstLineBox()) {
2601 if (containsStart) {
2602 // Go ahead and update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this
2604 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
2605 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2606 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2611 RootInlineBox* lastSelectedLine = 0;
2612 RootInlineBox* curr;
2613 for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2615 // Now paint the gaps for the lines.
2616 for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2617 LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
2618 LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
2620 if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
2621 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
2622 lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
2625 LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2626 logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
2627 LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2628 if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
2629 || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
2630 result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
2632 lastSelectedLine = curr;
2635 if (containsStart && !lastSelectedLine) {
2636 // VisibleSelection must start just after our last line.
2637 lastSelectedLine = lastRootBox();
2640 if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2641 // Go ahead and update our lastY to be the bottom of the last selected line.
2642 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2643 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2644 lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2649 LayoutUnit RenderBlockFlow::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2651 LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
2652 if (logicalLeft == logicalLeftOffsetForContent())
2653 return RenderBlock::logicalLeftSelectionOffset(rootBlock, position);
2655 RenderBlock* cb = this;
2656 while (cb != rootBlock) {
2657 logicalLeft += cb->logicalLeft();
2658 cb = cb->containingBlock();
2663 LayoutUnit RenderBlockFlow::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2665 LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
2666 if (logicalRight == logicalRightOffsetForContent())
2667 return RenderBlock::logicalRightSelectionOffset(rootBlock, position);
2669 RenderBlock* cb = this;
2670 while (cb != rootBlock) {
2671 logicalRight += cb->logicalLeft();
2672 cb = cb->containingBlock();
2674 return logicalRight;
2677 template <typename CharacterType>
2678 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2682 TextDirection textDirection = direction;
2683 bool directionalOverride = style->rtlOrdering() == VisualOrder;
2685 TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2686 if (textRunNeedsRenderingContext(font))
2687 run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2692 template <typename CharacterType>
2693 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2697 TextDirection textDirection = direction;
2698 bool directionalOverride = style->rtlOrdering() == VisualOrder;
2699 if (flags != DefaultTextRunFlags) {
2700 if (flags & RespectDirection)
2701 textDirection = style->direction();
2702 if (flags & RespectDirectionOverride)
2703 directionalOverride |= isOverride(style->unicodeBidi());
2706 TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2707 if (textRunNeedsRenderingContext(font))
2708 run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2713 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2715 return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2718 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2720 return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2723 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2726 return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction, expansion);
2727 return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction, expansion);
2730 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2732 ASSERT(offset + length <= text->textLength());
2734 return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction, expansion);
2735 return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction, expansion);
2738 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2740 unsigned length = string.length();
2742 return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, direction, expansion, flags);
2743 if (string.is8Bit())
2744 return constructTextRunInternal(context, font, string.characters8(), length, style, direction, expansion, flags);
2745 return constructTextRunInternal(context, font, string.characters16(), length, style, direction, expansion, flags);
2748 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2750 bool hasStrongDirectionality;
2751 return constructTextRun(context, font, string, style,
2752 determineDirectionality(string, hasStrongDirectionality),
2756 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
2758 ASSERT(offset + length <= text->textLength());
2759 TextRun run = text->is8Bit()
2760 ? constructTextRunInternal(context, font, text->characters8() + offset, length, style, LTR, expansion)
2761 : constructTextRunInternal(context, font, text->characters16() + offset, length, style, LTR, expansion);
2762 bool hasStrongDirectionality;
2763 run.setDirection(directionForRun(run, hasStrongDirectionality));
2767 RootInlineBox* RenderBlockFlow::createRootInlineBox()
2769 return new RootInlineBox(*this);
2772 void RenderBlockFlow::createOrDestroyMultiColumnFlowThreadIfNeeded()
2774 if (!document().regionBasedColumnsEnabled())
2777 bool needsFlowThread = style()->specifiesColumns();
2778 if (needsFlowThread != static_cast<bool>(multiColumnFlowThread())) {
2779 if (needsFlowThread) {
2780 RenderMultiColumnFlowThread* flowThread = RenderMultiColumnFlowThread::createAnonymous(document(), style());
2781 addChild(flowThread);
2782 flowThread->populate();
2783 RenderBlockFlowRareData& rareData = ensureRareData();
2784 ASSERT(!rareData.m_multiColumnFlowThread);
2785 rareData.m_multiColumnFlowThread = flowThread;
2787 multiColumnFlowThread()->evacuateAndDestroy();
2788 ASSERT(!multiColumnFlowThread());
2793 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
2798 m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
2802 } // namespace WebCore