Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / RenderBlockFlow.cpp
1 /*
2  * Copyright (C) 2013 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
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
13  * distribution.
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.
17  *
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.
29  */
30
31 #include "config.h"
32 #include "core/rendering/RenderBlockFlow.h"
33
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"
47
48 using namespace std;
49
50 namespace WebCore {
51
52 bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
53
54 struct SameSizeAsMarginInfo {
55     uint16_t bitfields;
56     LayoutUnit margins[2];
57 };
58
59 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
60
61 class MarginInfo {
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;
67
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;
72
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;
78
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;
81
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;
87
88     bool m_discardMargin : 1;
89
90     // These flags track the previous maximal positive and negative margins.
91     LayoutUnit m_positiveMargin;
92     LayoutUnit m_negativeMargin;
93
94 public:
95     MarginInfo(RenderBlockFlow*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
96
97     void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
98     void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
99     void clearMargin()
100     {
101         m_positiveMargin = 0;
102         m_negativeMargin = 0;
103     }
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)
110     {
111         ASSERT(!m_discardMargin);
112         if (p > m_positiveMargin)
113             m_positiveMargin = p;
114     }
115     void setNegativeMarginIfLarger(LayoutUnit n)
116     {
117         ASSERT(!m_discardMargin);
118         if (n > m_negativeMargin)
119             m_negativeMargin = n;
120     }
121
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; }
126
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; }
141 };
142 static bool inNormalFlow(RenderBox* child)
143 {
144     RenderBlock* curr = child->containingBlock();
145     RenderView* renderView = child->view();
146     while (curr && curr != renderView) {
147         if (curr->hasColumns() || curr->isRenderFlowThread())
148             return true;
149         if (curr->isFloatingOrOutOfFlowPositioned())
150             return false;
151         curr = curr->containingBlock();
152     }
153     return true;
154 }
155
156 RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
157     : RenderBlock(node)
158 {
159     COMPILE_ASSERT(sizeof(MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
160 }
161
162 RenderBlockFlow::~RenderBlockFlow()
163 {
164 }
165
166 RenderBlockFlow* RenderBlockFlow::createAnonymous(Document* document)
167 {
168     RenderBlockFlow* renderer = new RenderBlockFlow(0);
169     renderer->setDocumentForAnonymous(document);
170     return renderer;
171 }
172
173 RenderObject* RenderBlockFlow::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
174 {
175     RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread();
176     if (!flowThread)
177         return 0;
178     setLogicalTopForChild(flowThread, borderBefore() + paddingBefore());
179     flowThread->layoutColumns(relayoutChildren, layoutScope);
180     determineLogicalLeftPositionForChild(flowThread);
181     return flowThread;
182 }
183
184 bool RenderBlockFlow::updateLogicalWidthAndColumnWidth()
185 {
186     bool relayoutChildren = RenderBlock::updateLogicalWidthAndColumnWidth();
187     if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
188         if (flowThread->computeColumnCountAndWidth())
189             return true;
190     }
191     return relayoutChildren;
192 }
193
194 void RenderBlockFlow::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
195 {
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();
204
205         if (!pageLogicalHeight) {
206             LayoutUnit oldLogicalHeight = logicalHeight();
207             setLogicalHeight(0);
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;
215             }
216             setLogicalHeight(oldLogicalHeight);
217         }
218         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
219             colInfo->setColumnHeight(pageLogicalHeight);
220             pageLogicalHeightChanged = true;
221         }
222
223         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
224             colInfo->clearForcedBreaks();
225     } else if (isRenderFlowThread()) {
226         RenderFlowThread* flowThread = toRenderFlowThread(this);
227
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);
238
239         pageLogicalHeightChanged = flowThread->pageLogicalSizeChanged();
240     }
241 }
242
243 bool RenderBlockFlow::shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const
244 {
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);
258         }
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));
262     }
263
264     if (columnHeight && columnHeight != pageLogicalHeight) {
265         pageLogicalHeight = columnHeight;
266         return true;
267     }
268
269     return false;
270 }
271
272 void RenderBlockFlow::setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight)
273 {
274     ColumnInfo* colInfo = columnInfo();
275     if (pageLogicalHeight)
276         colInfo->setColumnCountAndHeight(count, pageLogicalHeight);
277
278     if (columnCount(colInfo)) {
279         setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
280         m_overflow.clear();
281     }
282 }
283
284 bool RenderBlockFlow::isSelfCollapsingBlock() const
285 {
286     m_hasOnlySelfCollapsingChildren = RenderBlock::isSelfCollapsingBlock();
287     return m_hasOnlySelfCollapsingChildren;
288 }
289
290 void RenderBlockFlow::layoutBlock(bool relayoutChildren)
291 {
292     ASSERT(needsLayout());
293     ASSERT(isInlineBlockOrInlineTable() || !isInline());
294
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;
299
300     if (!relayoutChildren && simplifiedLayout())
301         return;
302
303     SubtreeLayoutScope layoutScope(*this);
304
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.
309     bool done = false;
310     LayoutUnit pageLogicalHeight = 0;
311     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
312     while (!done)
313         done = layoutBlockFlow(relayoutChildren, pageLogicalHeight, layoutScope);
314
315     fitBorderToLinesIfNeeded();
316
317     RenderView* renderView = view();
318     if (renderView->layoutState()->pageLogicalHeight())
319         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(*this, logicalTop()));
320
321     updateLayerTransform();
322
323     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
324     // we overflow or not.
325     updateScrollInfoAfterLayout();
326
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);
332         else
333             repaintOverflow();
334     }
335     clearNeedsLayout();
336 }
337
338 inline bool RenderBlockFlow::layoutBlockFlow(bool relayoutChildren, LayoutUnit &pageLogicalHeight, SubtreeLayoutScope& layoutScope)
339 {
340     LayoutUnit oldLeft = logicalLeft();
341     if (updateLogicalWidthAndColumnWidth())
342         relayoutChildren = true;
343
344     rebuildFloatsFromIntruding();
345
346     bool pageLogicalHeightChanged = false;
347     bool hasSpecifiedPageLogicalHeight = false;
348     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
349     if (pageLogicalHeightChanged)
350         relayoutChildren = true;
351
352     LayoutStateMaintainer statePusher(*this, locationOffset(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
353
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.
361     //
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);
369     }
370
371     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
372     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
373     LayoutUnit previousHeight = logicalHeight();
374     setLogicalHeight(beforeEdge);
375
376     m_repaintLogicalTop = 0;
377     m_repaintLogicalBottom = 0;
378     if (!firstChild() && !isAnonymousBlock())
379         setChildrenInline(true);
380
381     FastTextAutosizer::LayoutScope fastTextAutosizerLayoutScope(this);
382
383     if (childrenInline())
384         layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom, afterEdge);
385     else
386         layoutBlockChildren(relayoutChildren, layoutScope, beforeEdge, afterEdge);
387
388     // Expand our intrinsic height to encompass floats.
389     if (lowestFloatLogicalBottom() > (logicalHeight() - afterEdge) && createsBlockFormattingContext())
390         setLogicalHeight(lowestFloatLogicalBottom() + afterEdge);
391
392     if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread()) {
393         if (flowThread->recalculateColumnHeights()) {
394             setChildNeedsLayout(MarkOnlyThis);
395             return false;
396         }
397     } else if (hasColumns()) {
398         OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
399         if (childrenInline())
400             addOverflowFromInlineChildren();
401         else
402             addOverflowFromBlockChildren();
403         LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
404         m_overflow = savedOverflow.release();
405
406         if (!hasSpecifiedPageLogicalHeight && shouldRelayoutForPagination(pageLogicalHeight, layoutOverflowLogicalBottom)) {
407             setEverHadLayout(true);
408             return false;
409         }
410
411         setColumnCountAndHeight(ceilf(layoutOverflowLogicalBottom.toFloat() / pageLogicalHeight.toFloat()), pageLogicalHeight.toFloat());
412     }
413
414     if (shouldBreakAtLineToAvoidWidow()) {
415         setEverHadLayout(true);
416         return false;
417     }
418
419     // Calculate our new height.
420     LayoutUnit oldHeight = logicalHeight();
421     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
422
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)
431                     break;
432                 addOverhangingFloats(block, false);
433             }
434         }
435     }
436
437     bool heightChanged = (previousHeight != newHeight);
438     if (heightChanged)
439         relayoutChildren = true;
440
441     layoutPositionedObjects(relayoutChildren || isDocumentElement(), oldLeft != logicalLeft() ? ForcedLayoutAfterContainingBlockMoved : DefaultLayout);
442
443     computeRegionRangeForBlock(flowThreadContainingBlock());
444
445     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
446     computeOverflow(oldClientAfterEdge);
447
448     return true;
449 }
450
451 void RenderBlockFlow::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
452 {
453     LayoutUnit startPosition = borderStart() + paddingStart();
454     if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
455         startPosition -= verticalScrollbarWidth();
456     LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
457
458     // Add in our start margin.
459     LayoutUnit childMarginStart = marginStartForChild(child);
460     LayoutUnit newPosition = startPosition + childMarginStart;
461
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));
466
467     setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
468 }
469
470 void RenderBlockFlow::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
471 {
472     if (isHorizontalWritingMode()) {
473         if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
474             view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
475         child->setX(logicalLeft);
476     } else {
477         if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
478             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
479         child->setY(logicalLeft);
480     }
481 }
482
483 void RenderBlockFlow::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
484 {
485     if (isHorizontalWritingMode()) {
486         if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
487             view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
488         child->setY(logicalTop);
489     } else {
490         if (applyDelta == ApplyLayoutDelta && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
491             view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
492         child->setX(logicalTop);
493     }
494 }
495
496 void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom)
497 {
498     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
499     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
500
501     // The child is a normal flow object. Compute the margins we will use for collapsing now.
502     child->computeAndSetBlockDirectionMargins(this);
503
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);
509
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);
513
514 #if !ASSERT_DISABLED
515     LayoutSize oldLayoutDelta = RuntimeEnabledFeatures::repaintAfterLayoutEnabled() ? LayoutSize() : view()->layoutDelta();
516 #endif
517     // Go ahead and position the child as though it didn't collapse with the top.
518     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
519
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
533         // layout.
534         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
535         if (fb > logicalTopEstimate)
536             markDescendantsWithFloats = true;
537     }
538
539     if (childRenderBlockFlow) {
540         if (markDescendantsWithFloats)
541             childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
542         if (!child->isWritingModeRoot())
543             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
544     }
545
546     SubtreeLayoutScope layoutScope(*child);
547     if (!child->needsLayout())
548         child->markForPaginationRelayoutIfNeeded(layoutScope);
549
550     bool childHadLayout = child->everHadLayout();
551     bool childNeededLayout = child->needsLayout();
552     if (childNeededLayout)
553         child->layout();
554
555     // Cache if we are at the top of the block right now.
556     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
557     bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
558
559     // Now determine the correct ypos based off examination of collapsing margin
560     // values.
561     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo, childIsSelfCollapsing);
562
563     // Now check for clear.
564     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear, childIsSelfCollapsing);
565
566     bool paginated = view()->layoutState()->isPaginated();
567     if (paginated) {
568         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
569             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
570     }
571
572     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
573
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);
585         }
586
587         if (childRenderBlock) {
588             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
589                 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
590             if (!child->needsLayout())
591                 child->markForPaginationRelayoutIfNeeded(layoutScope);
592         }
593
594         // Our guess was wrong. Make the child lay itself out again.
595         child->layoutIfNeeded();
596     }
597
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);
604
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);
609
610     // Now place the child in the correct left position
611     determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
612
613     LayoutSize childOffset = child->location() - oldRect.location();
614
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();
620     }
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);
625
626     if (childOffset.width() || childOffset.height()) {
627         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
628             view()->addLayoutDelta(childOffset);
629
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);
637     }
638
639     if (!childHadLayout && child->checkForRepaint()) {
640         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
641             child->repaint();
642         child->repaintOverhangingFloats(true);
643     }
644
645     if (paginated) {
646         // Check for an after page/column break.
647         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
648         if (newHeight != height())
649             setLogicalHeight(newHeight);
650     }
651
652     if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
653         ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
654     }
655 }
656
657 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
658 {
659     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
660
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
663         // position.
664         setLogicalHeight(logicalTopAfterClear);
665         setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
666
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);
673         }
674
675         SubtreeLayoutScope layoutScope(*child);
676
677         if (childRenderBlock) {
678             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
679                 toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
680             if (!child->needsLayout())
681                 child->markForPaginationRelayoutIfNeeded(layoutScope);
682         }
683
684         // Our guess was wrong. Make the child lay itself out again.
685         child->layoutIfNeeded();
686     }
687
688     LayoutUnit oldTop = logicalTopAfterClear;
689
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);
692
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
703             // than necessary.
704             setPageBreak(result, spaceShortage);
705         }
706     }
707
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);
711
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();
718
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);
729         } else {
730             result += paginationStrut;
731         }
732     }
733
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));
736
737     // Return the final adjusted logical top.
738     return result;
739 }
740
741 void RenderBlockFlow::rebuildFloatsFromIntruding()
742 {
743     if (m_floatingObjects)
744         m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
745
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());
754         }
755     }
756
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();
761         }
762         if (!oldIntrudingFloatSet.isEmpty())
763             markAllDescendantsWithFloatsForLayout();
764         return;
765     }
766
767     RendererToFloatInfoMap floatMap;
768
769     if (m_floatingObjects) {
770         if (childrenInline())
771             m_floatingObjects->moveAllToFloatInfoMap(floatMap);
772         else
773             m_floatingObjects->clear();
774     }
775
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())
780         return;
781
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();
792     }
793
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);
800
801     // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
802     if (prev) {
803         RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
804         logicalTopOffset -= blockFlow->logicalTop();
805         if (blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
806             addIntrudingFloats(blockFlow, 0, logicalTopOffset);
807     }
808
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));
824                     } else {
825                         if (logicalBottom != oldLogicalBottom) {
826                             changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
827                             changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
828                         }
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));
834                         }
835                     }
836
837                     floatMap.remove(floatingObject->renderer());
838                     if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
839                         ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
840                         oldFloatingObject->originatingLine()->markDirty();
841                     }
842                     delete oldFloatingObject;
843                 } else {
844                     changeLogicalTop = 0;
845                     changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
846                 }
847             }
848         }
849
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));
856             }
857         }
858         deleteAllValues(floatMap);
859
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();
866         } else {
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();
873         }
874     }
875 }
876
877 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, SubtreeLayoutScope& layoutScope, LayoutUnit beforeEdge, LayoutUnit afterEdge)
878 {
879     dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
880
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);
883
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);
888
889     LayoutUnit previousFloatLogicalBottom = 0;
890
891     RenderBox* next = firstChildBox();
892     RenderBox* lastNormalFlowChild = 0;
893
894     while (next) {
895         RenderBox* child = next;
896         next = child->nextSiblingBox();
897
898         // FIXME: this should only be set from clearNeedsLayout crbug.com/361250
899         child->setLayoutDidGetCalled(true);
900
901         if (childToExclude == child)
902             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
903
904         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
905
906         if (child->isOutOfFlowPositioned()) {
907             child->containingBlock()->insertPositionedObject(child);
908             adjustPositionedBlock(child, marginInfo);
909             continue;
910         }
911         if (child->isFloating()) {
912             insertFloatingObject(child);
913             adjustFloatingBlock(marginInfo);
914             continue;
915         }
916
917         // Lay out the child.
918         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom);
919         lastNormalFlowChild = child;
920     }
921
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);
925 }
926
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)
936 {
937     RenderStyle* blockStyle = blockFlow->style();
938     ASSERT(blockFlow->isRenderView() || blockFlow->parent());
939     m_canCollapseWithChildren = !blockFlow->createsBlockFormattingContext() && !blockFlow->isRenderFlowThread() && !blockFlow->isRenderView();
940
941     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
942
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;
949
950     m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody();
951
952     m_discardMargin = m_canCollapseMarginBeforeWithChildren && blockFlow->mustDiscardMarginBefore();
953
954     m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxPositiveMarginBefore() : LayoutUnit();
955     m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxNegativeMarginBefore() : LayoutUnit();
956 }
957
958 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox* child) const
959 {
960     LayoutUnit childBeforePositive = 0;
961     LayoutUnit childBeforeNegative = 0;
962     LayoutUnit childAfterPositive = 0;
963     LayoutUnit childAfterNegative = 0;
964
965     LayoutUnit beforeMargin = 0;
966     LayoutUnit afterMargin = 0;
967
968     RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
969
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();
978         } else {
979             beforeMargin = child->marginBefore();
980             afterMargin = child->marginAfter();
981         }
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();
990         } else {
991             beforeMargin = child->marginAfter();
992             afterMargin = child->marginBefore();
993         }
994     } else {
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);
999     }
1000
1001     // Resolve uncollapsing margins into their positive/negative buckets.
1002     if (beforeMargin) {
1003         if (beforeMargin > 0)
1004             childBeforePositive = beforeMargin;
1005         else
1006             childBeforeNegative = -beforeMargin;
1007     }
1008     if (afterMargin) {
1009         if (afterMargin > 0)
1010             childAfterPositive = afterMargin;
1011         else
1012             childAfterNegative = -afterMargin;
1013     }
1014
1015     return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
1016 }
1017
1018 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo, bool childIsSelfCollapsing)
1019 {
1020     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
1021     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
1022
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);
1025
1026     // Get the four margin values for the child and cache them.
1027     const RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1028
1029     // Get our max pos and neg top margins.
1030     LayoutUnit posTop = childMargins.positiveMarginBefore();
1031     LayoutUnit negTop = childMargins.negativeMarginBefore();
1032
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());
1038     }
1039
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);
1043
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()));
1051
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);
1059             }
1060
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);
1068             }
1069         } else {
1070             // The before margin of the container will also discard all the margins it is collapsing with.
1071             setMustDiscardMarginBefore();
1072         }
1073     }
1074
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();
1079     }
1080
1081     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1082         marginInfo.setHasMarginBeforeQuirk(topQuirk);
1083
1084     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1085     LayoutUnit logicalTop = beforeCollapseLogicalTop;
1086
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);
1096     }
1097
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);
1108
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());
1113
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;
1120             }
1121         }
1122     } else {
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();
1138         }
1139
1140         marginInfo.setDiscardMargin(childDiscardMarginAfter);
1141
1142         if (!marginInfo.discardMargin()) {
1143             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1144             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1145         } else {
1146             marginInfo.clearMargin();
1147         }
1148
1149         if (marginInfo.margin())
1150             marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
1151     }
1152
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));
1160     }
1161
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);
1170
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();
1177     }
1178
1179     return logicalTop;
1180 }
1181
1182 void RenderBlockFlow::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1183 {
1184     bool isHorizontal = isHorizontalWritingMode();
1185     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1186
1187     LayoutUnit logicalTop = logicalHeight();
1188     updateStaticInlinePositionForChild(child, logicalTop);
1189
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;
1196     }
1197
1198     RenderLayer* childLayer = child->layer();
1199     if (childLayer->staticBlockPosition() != logicalTop) {
1200         childLayer->setStaticBlockPosition(logicalTop);
1201         if (hasStaticBlockPosition)
1202             child->setChildNeedsLayout(MarkOnlyThis);
1203     }
1204 }
1205
1206 LayoutUnit RenderBlockFlow::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart)
1207 {
1208     LayoutUnit startPosition = startOffsetForContent();
1209
1210     // Add in our start margin.
1211     LayoutUnit oldPosition = startPosition + childMarginStart;
1212     LayoutUnit newPosition = oldPosition;
1213
1214     LayoutUnit blockOffset = logicalTopForChild(child);
1215     LayoutUnit startOff = startOffsetForLine(blockOffset, false, logicalHeightForChild(child));
1216
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;
1223     }
1224
1225     return newPosition - oldPosition;
1226 }
1227
1228 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing)
1229 {
1230     LayoutUnit heightIncrease = getClearDelta(child, yPos);
1231     if (!heightIncrease)
1232         return yPos;
1233
1234     if (childIsSelfCollapsing) {
1235         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1236
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()));
1245         } else {
1246             marginInfo.clearMargin();
1247         }
1248         marginInfo.setDiscardMargin(childDiscardMargin);
1249
1250         // CSS2.1 states:
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);
1256
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());
1265     } else {
1266         // Increase our height by the amount we had to clear.
1267         setLogicalHeight(logicalHeight() + heightIncrease);
1268     }
1269
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);
1275
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);
1278     }
1279
1280     return yPos + heightIncrease;
1281 }
1282
1283 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1284 {
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();
1290             return;
1291         }
1292
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()));
1296
1297         if (!marginInfo.hasMarginAfterQuirk())
1298             setHasMarginAfterQuirk(false);
1299
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);
1305         }
1306     }
1307 }
1308
1309 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1310 {
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)
1315         return;
1316
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;
1323         return;
1324     }
1325
1326     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1327     positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
1328     negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
1329
1330     if (!child->isRenderBlockFlow())
1331         return;
1332
1333     RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1334     if (childBlockFlow->childrenInline() || childBlockFlow->isWritingModeRoot())
1335         return;
1336
1337     MarginInfo childMarginInfo(childBlockFlow, childBlockFlow->borderBefore() + childBlockFlow->paddingBefore(), childBlockFlow->borderAfter() + childBlockFlow->paddingAfter());
1338     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1339         return;
1340
1341     RenderBox* grandchildBox = childBlockFlow->firstChildBox();
1342     for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1343         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1344             break;
1345     }
1346
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)
1349         return;
1350
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());
1358         }
1359     }
1360
1361     // Collapse the margin of the grandchild box with our own to produce an estimate.
1362     childBlockFlow->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1363 }
1364
1365 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1366 {
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);
1377         } else {
1378             // Use the cached collapsed margin values from a previous layout. Most of the time they
1379             // will be right.
1380             RenderBlockFlow::MarginValues marginValues = marginValuesForChild(child);
1381             positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
1382             negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
1383             discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1384         }
1385
1386         // Collapse the result with our current margins.
1387         if (!discardMarginBefore)
1388             logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
1389     }
1390
1391     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1392     // page.
1393     LayoutState* layoutState = view()->layoutState();
1394     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight())
1395         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1396
1397     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1398
1399     estimateWithoutPagination = logicalTopEstimate;
1400
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);
1404
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);
1407
1408         if (!child->selfNeedsLayout() && child->isRenderBlock())
1409             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
1410     }
1411
1412     return logicalTopEstimate;
1413 }
1414
1415 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
1416 {
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();
1422 }
1423
1424 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
1425 {
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.
1432     //
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);
1443 }
1444
1445 void RenderBlockFlow::handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1446 {
1447     marginInfo.setAtAfterSideOfBlock(true);
1448
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());
1454
1455     if (marginInfo.canCollapseMarginAfterWithChildren() && !marginInfo.canCollapseMarginAfterWithLastChild())
1456         marginInfo.setCanCollapseMarginAfterWithChildren(false);
1457
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());
1462
1463     // Now add in our bottom border/padding.
1464     setLogicalHeight(logicalHeight() + afterSide);
1465
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));
1469
1470     // Update our bottom collapsed margin info.
1471     setCollapsedBottomMargin(marginInfo);
1472 }
1473
1474 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1475 {
1476     if (style()->marginBeforeCollapse() == MDISCARD) {
1477         ASSERT(value);
1478         return;
1479     }
1480
1481     if (!m_rareData && !value)
1482         return;
1483
1484     if (!m_rareData)
1485         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1486
1487     m_rareData->m_discardMarginBefore = value;
1488 }
1489
1490 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1491 {
1492     if (style()->marginAfterCollapse() == MDISCARD) {
1493         ASSERT(value);
1494         return;
1495     }
1496
1497     if (!m_rareData && !value)
1498         return;
1499
1500     if (!m_rareData)
1501         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1502
1503     m_rareData->m_discardMarginAfter = value;
1504 }
1505
1506 bool RenderBlockFlow::mustDiscardMarginBefore() const
1507 {
1508     return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
1509 }
1510
1511 bool RenderBlockFlow::mustDiscardMarginAfter() const
1512 {
1513     return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
1514 }
1515
1516 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox* child) const
1517 {
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);
1523
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.
1526     return false;
1527 }
1528
1529 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox* child) const
1530 {
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);
1536
1537     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1538     return false;
1539 }
1540
1541 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1542 {
1543     if (!m_rareData) {
1544         if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(this))
1545             return;
1546         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1547     }
1548     m_rareData->m_margins.setPositiveMarginBefore(pos);
1549     m_rareData->m_margins.setNegativeMarginBefore(neg);
1550 }
1551
1552 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1553 {
1554     if (!m_rareData) {
1555         if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(this))
1556             return;
1557         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1558     }
1559     m_rareData->m_margins.setPositiveMarginAfter(pos);
1560     m_rareData->m_margins.setNegativeMarginAfter(neg);
1561 }
1562
1563 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox* child) const
1564 {
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;
1571
1572     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1573     return false;
1574 }
1575
1576 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox* child) const
1577 {
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;
1584
1585     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1586     return false;
1587 }
1588
1589 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
1590 {
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;
1604             } else {
1605                 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1606             }
1607         }
1608         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1609     }
1610     return logicalOffset;
1611 }
1612
1613 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1614 {
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();
1624
1625         // So our margin doesn't participate in the next collapsing steps.
1626         marginInfo.clearMargin();
1627
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;
1633             } else {
1634                 view()->layoutState()->addForcedColumnBreak(*child, logicalOffset);
1635             }
1636         }
1637         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1638     }
1639     return logicalOffset;
1640 }
1641
1642 void RenderBlockFlow::addOverflowFromFloats()
1643 {
1644     if (!m_floatingObjects)
1645         return;
1646
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)));
1653     }
1654 }
1655
1656 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1657 {
1658     RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
1659     if (!hasColumns() && (recomputeFloats || createsBlockFormattingContext() || hasSelfPaintingLayer()))
1660         addOverflowFromFloats();
1661 }
1662
1663 RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
1664 {
1665     RootInlineBox* rootBox = createRootInlineBox();
1666     m_lineBoxes.appendLineBox(rootBox);
1667
1668     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1669         if (AXObjectCache* cache = document().existingAXObjectCache())
1670             cache->recomputeIsIgnored(this);
1671     }
1672
1673     return rootBox;
1674 }
1675
1676 void RenderBlockFlow::deleteLineBoxTree()
1677 {
1678     if (containsFloats())
1679         m_floatingObjects->clearLineBoxTreePointers();
1680     RenderBlock::deleteLineBoxTree();
1681 }
1682
1683 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
1684 {
1685     if (!everHadLayout() && !containsFloats())
1686         return;
1687
1688     MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
1689     setChildNeedsLayout(markParents);
1690
1691     if (floatToRemove)
1692         removeFloatingObject(floatToRemove);
1693
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())
1698                 continue;
1699             if (!child->isRenderBlockFlow()) {
1700                 RenderBlock* childBlock = toRenderBlock(child);
1701                 if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
1702                     childBlock->setChildNeedsLayout(markParents);
1703                 continue;
1704             }
1705             RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1706             if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
1707                 childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
1708         }
1709     }
1710 }
1711
1712 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
1713 {
1714     if (!m_floatingObjects)
1715         return;
1716
1717     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1718     FloatingObjectSetIterator end = floatingObjectSet.end();
1719
1720     for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
1721         if (!next->isRenderBlockFlow() || avoidsOrIgnoresFloats())
1722             continue;
1723
1724         RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1725         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1726             RenderBox* floatingBox = (*it)->renderer();
1727             if (floatToRemove && floatingBox != floatToRemove)
1728                 continue;
1729             if (nextBlock->containsFloat(floatingBox))
1730                 nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
1731         }
1732     }
1733 }
1734
1735 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
1736 {
1737     // There is no need to compute clearance if we have no floats.
1738     if (!containsFloats())
1739         return 0;
1740
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()) {
1745     case CNONE:
1746         break;
1747     case CLEFT:
1748         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
1749         break;
1750     case CRIGHT:
1751         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
1752         break;
1753     case CBOTH:
1754         logicalBottom = lowestFloatLogicalBottom();
1755         break;
1756     }
1757
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;
1762         while (true) {
1763             LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
1764             if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent())
1765                 return newLogicalTop - logicalTop;
1766
1767             LayoutRect borderBox = child->borderBoxRect();
1768             LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1769
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();
1775
1776             child->setLogicalTop(newLogicalTop);
1777             child->updateLogicalWidth();
1778             borderBox = child->borderBoxRect();
1779             LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1780
1781             child->setLogicalTop(childOldLogicalTop);
1782             child->setLogicalWidth(childOldLogicalWidth);
1783             child->setMarginLeft(childOldMarginLeft);
1784             child->setMarginRight(childOldMarginRight);
1785
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;
1793             }
1794
1795             newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
1796             ASSERT(newLogicalTop >= logicalTop);
1797             if (newLogicalTop < logicalTop)
1798                 break;
1799         }
1800         ASSERT_NOT_REACHED();
1801     }
1802     return result;
1803 }
1804
1805 void RenderBlockFlow::createFloatingObjects()
1806 {
1807     m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
1808 }
1809
1810 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
1811 {
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();
1817
1818     RenderBlock::styleWillChange(diff, newStyle);
1819 }
1820
1821 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1822 {
1823     RenderBlock::styleDidChange(diff, oldStyle);
1824
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();
1834
1835         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
1836             if (curr->isRenderBlockFlow()) {
1837                 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
1838
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;
1844                             break;
1845                         }
1846                     }
1847                 }
1848             }
1849         }
1850
1851         parentBlockFlow->markAllDescendantsWithFloatsForLayout();
1852         parentBlockFlow->markSiblingsWithFloatsForLayout();
1853     }
1854
1855     if (diff.needsFullLayout() || !oldStyle)
1856         createOrDestroyMultiColumnFlowThreadIfNeeded();
1857 }
1858
1859 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
1860 {
1861     if (child->style()->isOriginalDisplayInlineType())
1862         setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
1863     else
1864         setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent());
1865 }
1866
1867 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
1868 {
1869     child->layer()->setStaticInlinePosition(inlinePosition);
1870 }
1871
1872 void RenderBlockFlow::addChild(RenderObject* newChild, RenderObject* beforeChild)
1873 {
1874     if (RenderMultiColumnFlowThread* flowThread = multiColumnFlowThread())
1875         return flowThread->addChild(newChild, beforeChild);
1876     RenderBlock::addChild(newChild, beforeChild);
1877 }
1878
1879 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1880 {
1881     RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
1882     moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
1883
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
1899     // displayed.
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();
1904
1905         const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1906         FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1907
1908         for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1909             FloatingObject* floatingObject = *it;
1910
1911             // Don't insert the object again if it's already in the list
1912             if (toBlockFlow->containsFloat(floatingObject->renderer()))
1913                 continue;
1914
1915             toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
1916         }
1917     }
1918
1919 }
1920
1921 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
1922 {
1923     // Repaint any overhanging floats (if we know we're the one to paint them).
1924     // Otherwise, bail out.
1925     if (!hasOverhangingFloats())
1926         return;
1927
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)))) {
1941
1942             RenderBox* floatingRenderer = floatingObject->renderer();
1943             if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
1944                 floatingRenderer->setShouldDoFullRepaintAfterLayout(true);
1945             else
1946                 floatingRenderer->repaint();
1947
1948             floatingRenderer->repaintOverhangingFloats(false);
1949         }
1950     }
1951 }
1952
1953 void RenderBlockFlow::repaintOverflow()
1954 {
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());
1965     }
1966
1967     LayoutRect repaintRect;
1968     if (isHorizontalWritingMode())
1969         repaintRect = LayoutRect(repaintLogicalLeft, m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop);
1970     else
1971         repaintRect = LayoutRect(m_repaintLogicalTop, repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1972
1973     // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1974     adjustRectForColumns(repaintRect);
1975
1976     if (hasOverflowClip()) {
1977         // Adjust repaint rect for scroll offset
1978         repaintRect.move(-scrolledContentOffset());
1979
1980         // Don't allow this rect to spill out of our overflow box.
1981         repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1982     }
1983
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;
1988
1989         repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1990         if (hasReflection())
1991             repaintRectangle(reflectedRect(repaintRect));
1992     }
1993
1994     m_repaintLogicalTop = 0;
1995     m_repaintLogicalBottom = 0;
1996 }
1997
1998 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
1999 {
2000     if (!m_floatingObjects)
2001         return;
2002
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);
2023             }
2024         }
2025     }
2026 }
2027
2028 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
2029 {
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));
2041         }
2042     }
2043 }
2044
2045 void RenderBlockFlow::clearFloats(EClear clear)
2046 {
2047     positionNewFloats();
2048     // set y position
2049     LayoutUnit newY = 0;
2050     switch (clear) {
2051     case CLEFT:
2052         newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2053         break;
2054     case CRIGHT:
2055         newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2056         break;
2057     case CBOTH:
2058         newY = lowestFloatLogicalBottom();
2059     default:
2060         break;
2061     }
2062     if (height() < newY)
2063         setLogicalHeight(newY);
2064 }
2065
2066 bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
2067 {
2068     return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
2069 }
2070
2071 void RenderBlockFlow::removeFloatingObjects()
2072 {
2073     if (!m_floatingObjects)
2074         return;
2075
2076     markSiblingsWithFloatsForLayout();
2077
2078     m_floatingObjects->clear();
2079 }
2080
2081 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2082 {
2083     if (!style()->isFlippedBlocksWritingMode())
2084         return point;
2085
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
2088     // case.
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());
2092 }
2093
2094 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2095 {
2096     LayoutUnit offset = fixedOffset;
2097     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2098         offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2099     return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2100 }
2101
2102 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2103 {
2104     LayoutUnit offset = fixedOffset;
2105     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2106         offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2107     return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2108 }
2109
2110 LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2111 {
2112     LayoutUnit left = offsetFromFloats;
2113
2114     if (applyTextIndent && style()->isLeftToRightDirection())
2115         left += textIndentOffset();
2116
2117     return left;
2118 }
2119
2120 LayoutUnit RenderBlockFlow::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2121 {
2122     LayoutUnit right = offsetFromFloats;
2123
2124     if (applyTextIndent && !style()->isLeftToRightDirection())
2125         right -= textIndentOffset();
2126
2127     return right;
2128 }
2129
2130 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
2131 {
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();
2136
2137     LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2138
2139     LayoutUnit floatLogicalLeft;
2140
2141     bool insideFlowThread = flowThreadContainingBlock();
2142
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);
2155             }
2156         }
2157         floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2158     } else {
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);
2170             }
2171         }
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);
2176     }
2177
2178     return LayoutPoint(floatLogicalLeft, logicalTopOffset);
2179 }
2180
2181 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
2182 {
2183     ASSERT(floatBox->isFloating());
2184
2185     // Create the list of special objects if we don't aleady have one
2186     if (!m_floatingObjects) {
2187         createFloatingObjects();
2188     } else {
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())
2193             return *it;
2194     }
2195
2196     // Create the special object entry & append it to the list
2197
2198     OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
2199
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);
2205
2206     bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2207     if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
2208         floatBox->layoutIfNeeded();
2209     } else {
2210         floatBox->updateLogicalWidth();
2211         floatBox->computeAndSetBlockDirectionMargins(this);
2212     }
2213
2214     setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2215
2216     return m_floatingObjects->add(newObj.release());
2217 }
2218
2219 void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
2220 {
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);
2229
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();
2233                 } else {
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);
2238                 }
2239                 if (floatingObject->originatingLine()) {
2240                     if (!selfNeedsLayout()) {
2241                         ASSERT(floatingObject->originatingLine()->renderer() == this);
2242                         floatingObject->originatingLine()->markDirty();
2243                     }
2244 #if !ASSERT_DISABLED
2245                     floatingObject->setOriginatingLine(0);
2246 #endif
2247                 }
2248                 markLinesDirtyInBlockRange(0, logicalBottom);
2249             }
2250             m_floatingObjects->remove(floatingObject);
2251         }
2252     }
2253 }
2254
2255 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2256 {
2257     if (!containsFloats())
2258         return;
2259
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())
2265             break;
2266         curr = floatingObjectSet.last();
2267     }
2268 }
2269
2270 bool RenderBlockFlow::positionNewFloats()
2271 {
2272     if (!m_floatingObjects)
2273         return false;
2274
2275     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2276     if (floatingObjectSet.isEmpty())
2277         return false;
2278
2279     // If all floats have already been positioned, then we have no work to do.
2280     if (floatingObjectSet.last()->isPlaced())
2281         return false;
2282
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) {
2291         --it;
2292         if ((*it)->isPlaced()) {
2293             lastPlacedFloatingObject = *it;
2294             ++it;
2295             break;
2296         }
2297     }
2298
2299     LayoutUnit logicalTop = logicalHeight();
2300
2301     // The float cannot start above the top position of the last positioned float.
2302     if (lastPlacedFloatingObject)
2303         logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
2304
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)
2312             continue;
2313
2314         RenderBox* childBox = floatingObject->renderer();
2315
2316         // FIXME Investigate if this can be removed. crbug.com/370006
2317         childBox->setMayNeedInvalidation(true);
2318
2319         LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2320         LayoutRect oldRect = childBox->frameRect();
2321
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);
2326
2327         LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
2328
2329         setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2330
2331         setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2332         setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2333
2334         SubtreeLayoutScope layoutScope(*childBox);
2335         LayoutState* layoutState = view()->layoutState();
2336         bool isPaginated = layoutState->isPaginated();
2337         if (isPaginated && !childBox->needsLayout())
2338             childBox->markForPaginationRelayoutIfNeeded(layoutScope);
2339
2340         childBox->layoutIfNeeded();
2341
2342         if (isPaginated) {
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);
2346
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);
2354             }
2355
2356             if (newLogicalTop != floatLogicalLocation.y()) {
2357                 floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
2358
2359                 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2360                 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2361
2362                 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2363                 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2364
2365                 if (childBlock)
2366                     childBlock->setChildNeedsLayout(MarkOnlyThis);
2367                 childBox->layoutIfNeeded();
2368             }
2369         }
2370
2371         setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
2372
2373         setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2374
2375         m_floatingObjects->addPlacedObject(floatingObject);
2376
2377         if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
2378             shapeOutside->setReferenceBoxLogicalSize(logicalSizeForChild(childBox));
2379
2380         // If the child moved, we have to repaint it.
2381         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()
2382             && childBox->checkForRepaintDuringLayout())
2383             childBox->repaintDuringLayoutIfMoved(oldRect);
2384     }
2385     return true;
2386 }
2387
2388 bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
2389 {
2390     if (!m_floatingObjects || hasColumns() || !parent())
2391         return false;
2392
2393     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2394     FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
2395     if (it == floatingObjectSet.end())
2396         return false;
2397
2398     return logicalBottomForFloat(*it) > logicalHeight();
2399 }
2400
2401 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2402 {
2403     ASSERT(!avoidsFloats());
2404
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())
2407         return;
2408
2409     // If the parent or previous sibling doesn't have any floats to add, don't bother.
2410     if (!prev->m_floatingObjects)
2411         return;
2412
2413     logicalLeftOffset += marginLogicalLeft();
2414
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();
2424
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()));
2433
2434                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
2435             }
2436         }
2437     }
2438 }
2439
2440 void RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
2441 {
2442     // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2443     if (!child->containsFloats() || child->isRenderRegion() || child->createsBlockFormattingContext())
2444         return;
2445
2446     LayoutUnit childLogicalTop = child->logicalTop();
2447     LayoutUnit childLogicalLeft = child->logicalLeft();
2448
2449     // Floats that will remain the child's responsibility to paint should factor into its
2450     // overflow.
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;
2456
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;
2462
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);
2469                     shouldPaint = true;
2470                 }
2471                 // We create the floating object list lazily.
2472                 if (!m_floatingObjects)
2473                     createFloatingObjects();
2474
2475                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
2476             }
2477         } else {
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
2482                 // layer.
2483                 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2484                 // it should paint.
2485                 floatingObject->setShouldPaint(true);
2486             }
2487
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
2489             // child now.
2490             if (floatingObject->isDescendant())
2491                 child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
2492         }
2493     }
2494 }
2495
2496 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2497 {
2498     if (!m_floatingObjects)
2499         return 0;
2500
2501     return m_floatingObjects->lowestFloatLogicalBottom(floatType);
2502 }
2503
2504 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
2505 {
2506     if (!m_floatingObjects)
2507         return logicalHeight;
2508
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;
2521         }
2522         if (floatLogicalBottom > logicalHeight)
2523             logicalBottom = logicalBottom ? min(floatLogicalBottom, logicalBottom) : floatLogicalBottom;
2524     }
2525
2526     return logicalBottom;
2527 }
2528
2529 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2530 {
2531     if (!m_floatingObjects)
2532         return false;
2533
2534     LayoutPoint adjustedLocation = accumulatedOffset;
2535     if (isRenderView()) {
2536         adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
2537     }
2538
2539     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2540     FloatingObjectSetIterator begin = floatingObjectSet.begin();
2541     for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
2542         --it;
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));
2550                 return true;
2551             }
2552         }
2553     }
2554
2555     return false;
2556 }
2557
2558 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2559 {
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);
2572             }
2573         }
2574     }
2575 }
2576
2577 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2578 {
2579     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2580         return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2581
2582     return fixedOffset;
2583 }
2584
2585 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2586 {
2587     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2588         return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2589
2590     return fixedOffset;
2591 }
2592
2593 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2594     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2595 {
2596     GapRects result;
2597
2598     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2599
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
2603             // case.
2604             lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
2605             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2606             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2607         }
2608         return result;
2609     }
2610
2611     RootInlineBox* lastSelectedLine = 0;
2612     RootInlineBox* curr;
2613     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2614
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();
2619
2620         if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
2621             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
2622                 lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
2623         }
2624
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));
2631
2632         lastSelectedLine = curr;
2633     }
2634
2635     if (containsStart && !lastSelectedLine) {
2636         // VisibleSelection must start just after our last line.
2637         lastSelectedLine = lastRootBox();
2638     }
2639
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());
2645     }
2646     return result;
2647 }
2648
2649 LayoutUnit RenderBlockFlow::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2650 {
2651     LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
2652     if (logicalLeft == logicalLeftOffsetForContent())
2653         return RenderBlock::logicalLeftSelectionOffset(rootBlock, position);
2654
2655     RenderBlock* cb = this;
2656     while (cb != rootBlock) {
2657         logicalLeft += cb->logicalLeft();
2658         cb = cb->containingBlock();
2659     }
2660     return logicalLeft;
2661 }
2662
2663 LayoutUnit RenderBlockFlow::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2664 {
2665     LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
2666     if (logicalRight == logicalRightOffsetForContent())
2667         return RenderBlock::logicalRightSelectionOffset(rootBlock, position);
2668
2669     RenderBlock* cb = this;
2670     while (cb != rootBlock) {
2671         logicalRight += cb->logicalLeft();
2672         cb = cb->containingBlock();
2673     }
2674     return logicalRight;
2675 }
2676
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)
2679 {
2680     ASSERT(style);
2681
2682     TextDirection textDirection = direction;
2683     bool directionalOverride = style->rtlOrdering() == VisualOrder;
2684
2685     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2686     if (textRunNeedsRenderingContext(font))
2687         run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2688
2689     return run;
2690 }
2691
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)
2694 {
2695     ASSERT(style);
2696
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());
2704     }
2705
2706     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2707     if (textRunNeedsRenderingContext(font))
2708         run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2709
2710     return run;
2711 }
2712
2713 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2714 {
2715     return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2716 }
2717
2718 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2719 {
2720     return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2721 }
2722
2723 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2724 {
2725     if (text->is8Bit())
2726         return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction, expansion);
2727     return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction, expansion);
2728 }
2729
2730 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2731 {
2732     ASSERT(offset + length <= text->textLength());
2733     if (text->is8Bit())
2734         return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction, expansion);
2735     return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction, expansion);
2736 }
2737
2738 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2739 {
2740     unsigned length = string.length();
2741     if (!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);
2746 }
2747
2748 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2749 {
2750     bool hasStrongDirectionality;
2751     return constructTextRun(context, font, string, style,
2752         determineDirectionality(string, hasStrongDirectionality),
2753         expansion, flags);
2754 }
2755
2756 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
2757 {
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));
2764     return run;
2765 }
2766
2767 RootInlineBox* RenderBlockFlow::createRootInlineBox()
2768 {
2769     return new RootInlineBox(*this);
2770 }
2771
2772 void RenderBlockFlow::createOrDestroyMultiColumnFlowThreadIfNeeded()
2773 {
2774     if (!document().regionBasedColumnsEnabled())
2775         return;
2776
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;
2786         } else {
2787             multiColumnFlowThread()->evacuateAndDestroy();
2788             ASSERT(!multiColumnFlowThread());
2789         }
2790     }
2791 }
2792
2793 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
2794 {
2795     if (m_rareData)
2796         return *m_rareData;
2797
2798     m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
2799     return *m_rareData;
2800 }
2801
2802 } // namespace WebCore