Upstream version 5.34.104.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/LayoutRectRecorder.h"
39 #include "core/rendering/LayoutRepainter.h"
40 #include "core/rendering/RenderFlowThread.h"
41 #include "core/rendering/RenderLayer.h"
42 #include "core/rendering/RenderMultiColumnBlock.h"
43 #include "core/rendering/RenderText.h"
44 #include "core/rendering/RenderView.h"
45 #include "core/rendering/line/LineWidth.h"
46 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
47 #include "platform/text/BidiTextRun.h"
48
49 using namespace std;
50
51 namespace WebCore {
52
53 bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
54
55 struct SameSizeAsMarginInfo {
56     uint16_t bitfields;
57     LayoutUnit margins[2];
58 };
59
60 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
61
62 class MarginInfo {
63     // Collapsing flags for whether we can collapse our margins with our children's margins.
64     bool m_canCollapseWithChildren : 1;
65     bool m_canCollapseMarginBeforeWithChildren : 1;
66     bool m_canCollapseMarginAfterWithChildren : 1;
67     bool m_canCollapseMarginAfterWithLastChild: 1;
68
69     // Whether or not we are a quirky container, i.e., do we collapse away top and bottom
70     // margins in our container. Table cells and the body are the common examples. We
71     // also have a custom style property for Safari RSS to deal with TypePad blog articles.
72     bool m_quirkContainer : 1;
73
74     // This flag tracks whether we are still looking at child margins that can all collapse together at the beginning of a block.
75     // They may or may not collapse with the top margin of the block (|m_canCollapseTopWithChildren| tells us that), but they will
76     // always be collapsing with one another. This variable can remain set to true through multiple iterations
77     // as long as we keep encountering self-collapsing blocks.
78     bool m_atBeforeSideOfBlock : 1;
79
80     // This flag is set when we know we're examining bottom margins and we know we're at the bottom of the block.
81     bool m_atAfterSideOfBlock : 1;
82
83     // These variables are used to detect quirky margins that we need to collapse away (in table cells
84     // and in the body element).
85     bool m_hasMarginBeforeQuirk : 1;
86     bool m_hasMarginAfterQuirk : 1;
87     bool m_determinedMarginBeforeQuirk : 1;
88
89     bool m_discardMargin : 1;
90
91     // These flags track the previous maximal positive and negative margins.
92     LayoutUnit m_positiveMargin;
93     LayoutUnit m_negativeMargin;
94
95 public:
96     MarginInfo(RenderBlockFlow*, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding);
97
98     void setAtBeforeSideOfBlock(bool b) { m_atBeforeSideOfBlock = b; }
99     void setAtAfterSideOfBlock(bool b) { m_atAfterSideOfBlock = b; }
100     void clearMargin()
101     {
102         m_positiveMargin = 0;
103         m_negativeMargin = 0;
104     }
105     void setHasMarginBeforeQuirk(bool b) { m_hasMarginBeforeQuirk = b; }
106     void setHasMarginAfterQuirk(bool b) { m_hasMarginAfterQuirk = b; }
107     void setDeterminedMarginBeforeQuirk(bool b) { m_determinedMarginBeforeQuirk = b; }
108     void setPositiveMargin(LayoutUnit p) { ASSERT(!m_discardMargin); m_positiveMargin = p; }
109     void setNegativeMargin(LayoutUnit n) { ASSERT(!m_discardMargin); m_negativeMargin = n; }
110     void setPositiveMarginIfLarger(LayoutUnit p)
111     {
112         ASSERT(!m_discardMargin);
113         if (p > m_positiveMargin)
114             m_positiveMargin = p;
115     }
116     void setNegativeMarginIfLarger(LayoutUnit n)
117     {
118         ASSERT(!m_discardMargin);
119         if (n > m_negativeMargin)
120             m_negativeMargin = n;
121     }
122
123     void setMargin(LayoutUnit p, LayoutUnit n) { ASSERT(!m_discardMargin); m_positiveMargin = p; m_negativeMargin = n; }
124     void setCanCollapseMarginAfterWithChildren(bool collapse) { m_canCollapseMarginAfterWithChildren = collapse; }
125     void setCanCollapseMarginAfterWithLastChild(bool collapse) { m_canCollapseMarginAfterWithLastChild = collapse; }
126     void setDiscardMargin(bool value) { m_discardMargin = value; }
127
128     bool atBeforeSideOfBlock() const { return m_atBeforeSideOfBlock; }
129     bool canCollapseWithMarginBefore() const { return m_atBeforeSideOfBlock && m_canCollapseMarginBeforeWithChildren; }
130     bool canCollapseWithMarginAfter() const { return m_atAfterSideOfBlock && m_canCollapseMarginAfterWithChildren; }
131     bool canCollapseMarginBeforeWithChildren() const { return m_canCollapseMarginBeforeWithChildren; }
132     bool canCollapseMarginAfterWithChildren() const { return m_canCollapseMarginAfterWithChildren; }
133     bool canCollapseMarginAfterWithLastChild() const { return m_canCollapseMarginAfterWithLastChild; }
134     bool quirkContainer() const { return m_quirkContainer; }
135     bool determinedMarginBeforeQuirk() const { return m_determinedMarginBeforeQuirk; }
136     bool hasMarginBeforeQuirk() const { return m_hasMarginBeforeQuirk; }
137     bool hasMarginAfterQuirk() const { return m_hasMarginAfterQuirk; }
138     LayoutUnit positiveMargin() const { return m_positiveMargin; }
139     LayoutUnit negativeMargin() const { return m_negativeMargin; }
140     bool discardMargin() const { return m_discardMargin; }
141     LayoutUnit margin() const { return m_positiveMargin - m_negativeMargin; }
142 };
143 static bool inNormalFlow(RenderBox* child)
144 {
145     RenderBlock* curr = child->containingBlock();
146     RenderView* renderView = child->view();
147     while (curr && curr != renderView) {
148         if (curr->hasColumns() || curr->isRenderFlowThread())
149             return true;
150         if (curr->isFloatingOrOutOfFlowPositioned())
151             return false;
152         curr = curr->containingBlock();
153     }
154     return true;
155 }
156
157 RenderBlockFlow::RenderBlockFlow(ContainerNode* node)
158     : RenderBlock(node)
159 {
160     COMPILE_ASSERT(sizeof(MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
161 }
162
163 RenderBlockFlow::~RenderBlockFlow()
164 {
165 }
166
167 RenderBlockFlow* RenderBlockFlow::createAnonymous(Document* document)
168 {
169     RenderBlockFlow* renderer = new RenderBlockFlow(0);
170     renderer->setDocumentForAnonymous(document);
171     return renderer;
172 }
173
174 RenderBlockFlow* RenderBlockFlow::createAnonymousBlockFlow() const
175 {
176     return toRenderBlockFlow(createAnonymousWithParentRendererAndDisplay(this, BLOCK));
177 }
178
179 void RenderBlockFlow::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
180 {
181     ColumnInfo* colInfo = columnInfo();
182     if (hasColumns()) {
183         if (!pageLogicalHeight) {
184             LayoutUnit oldLogicalHeight = logicalHeight();
185             setLogicalHeight(0);
186             // We need to go ahead and set our explicit page height if one exists, so that we can
187             // avoid doing two layout passes.
188             updateLogicalHeight();
189             LayoutUnit columnHeight = contentLogicalHeight();
190             if (columnHeight > 0) {
191                 pageLogicalHeight = columnHeight;
192                 hasSpecifiedPageLogicalHeight = true;
193             }
194             setLogicalHeight(oldLogicalHeight);
195         }
196         if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
197             colInfo->setColumnHeight(pageLogicalHeight);
198             pageLogicalHeightChanged = true;
199         }
200
201         if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
202             colInfo->clearForcedBreaks();
203     } else if (isRenderFlowThread()) {
204         pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
205         pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
206     }
207 }
208
209 bool RenderBlockFlow::shouldRelayoutForPagination(LayoutUnit& pageLogicalHeight, LayoutUnit layoutOverflowLogicalBottom) const
210 {
211     // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
212     // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
213     ColumnInfo* colInfo = columnInfo();
214     LayoutUnit columnHeight = pageLogicalHeight;
215     const int minColumnCount = colInfo->forcedBreaks() + 1;
216     const int desiredColumnCount = colInfo->desiredColumnCount();
217     if (minColumnCount >= desiredColumnCount) {
218         // The forced page breaks are in control of the balancing. Just set the column height to the
219         // maximum page break distance.
220         if (!pageLogicalHeight) {
221             LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
222                 view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
223             columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
224         }
225     } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
226         // Now that we know the intrinsic height of the columns, we have to rebalance them.
227         columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
228     }
229
230     if (columnHeight && columnHeight != pageLogicalHeight) {
231         pageLogicalHeight = columnHeight;
232         return true;
233     }
234
235     return false;
236 }
237
238 void RenderBlockFlow::setColumnCountAndHeight(unsigned count, LayoutUnit pageLogicalHeight)
239 {
240     ColumnInfo* colInfo = columnInfo();
241     if (pageLogicalHeight)
242         colInfo->setColumnCountAndHeight(count, pageLogicalHeight);
243
244     if (columnCount(colInfo)) {
245         setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
246         m_overflow.clear();
247     }
248 }
249
250 bool RenderBlockFlow::isSelfCollapsingBlock() const
251 {
252     m_hasOnlySelfCollapsingChildren = RenderBlock::isSelfCollapsingBlock();
253     return m_hasOnlySelfCollapsingChildren;
254 }
255
256 void RenderBlockFlow::layoutBlock(bool relayoutChildren)
257 {
258     ASSERT(needsLayout());
259     ASSERT(isInlineBlockOrInlineTable() || !isInline());
260
261     // If we are self-collapsing with self-collapsing descendants this will get set to save us burrowing through our
262     // descendants every time in |isSelfCollapsingBlock|. We reset it here so that |isSelfCollapsingBlock| attempts to burrow
263     // at least once and so that it always gives a reliable result reflecting the latest layout.
264     m_hasOnlySelfCollapsingChildren = false;
265
266     if (!relayoutChildren && simplifiedLayout())
267         return;
268
269     SubtreeLayoutScope layoutScope(this);
270
271     // Multiple passes might be required for column and pagination based layout
272     // In the case of the old column code the number of passes will only be two
273     // however, in the newer column code the number of passes could equal the
274     // number of columns.
275     bool done = false;
276     LayoutUnit pageLogicalHeight = 0;
277     while (!done)
278         done = layoutBlockFlow(relayoutChildren, pageLogicalHeight, layoutScope);
279 }
280
281 inline bool RenderBlockFlow::layoutBlockFlow(bool relayoutChildren, LayoutUnit &pageLogicalHeight, SubtreeLayoutScope& layoutScope)
282 {
283     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
284
285     if (updateLogicalWidthAndColumnWidth())
286         relayoutChildren = true;
287
288     rebuildFloatsFromIntruding();
289
290     bool pageLogicalHeightChanged = false;
291     bool hasSpecifiedPageLogicalHeight = false;
292     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
293
294     RenderView* renderView = view();
295     LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
296
297     // Regions changing widths can force us to relayout our children.
298     RenderFlowThread* flowThread = flowThreadContainingBlock();
299     if (updateRegionsAndShapesLogicalSize(flowThread))
300         relayoutChildren = true;
301
302     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
303     // our current maximal positive and negative margins. These values are used when we
304     // are collapsed with adjacent blocks, so for example, if you have block A and B
305     // collapsing together, then you'd take the maximal positive margin from both A and B
306     // and subtract it from the maximal negative margin from both A and B to get the
307     // true collapsed margin. This algorithm is recursive, so when we finish layout()
308     // our block knows its current maximal positive/negative values.
309     //
310     // Start out by setting our margin values to our current margins. Table cells have
311     // no margins, so we don't fill in the values for table cells.
312     if (!isTableCell()) {
313         initMaxMarginValues();
314         setHasMarginBeforeQuirk(style()->hasMarginBeforeQuirk());
315         setHasMarginAfterQuirk(style()->hasMarginAfterQuirk());
316         setPaginationStrut(0);
317     }
318
319     LayoutUnit beforeEdge = borderBefore() + paddingBefore();
320     LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
321     LayoutUnit previousHeight = logicalHeight();
322     setLogicalHeight(beforeEdge);
323
324     m_repaintLogicalTop = 0;
325     m_repaintLogicalBottom = 0;
326     LayoutUnit maxFloatLogicalBottom = 0;
327     if (!firstChild() && !isAnonymousBlock())
328         setChildrenInline(true);
329
330     FastTextAutosizer::LayoutScope fastTextAutosizerLayoutScope(document(), this);
331
332     if (childrenInline())
333         layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom, afterEdge);
334     else
335         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope, beforeEdge, afterEdge);
336
337     if (frameView()->partialLayout().isStopping()) {
338         statePusher.pop();
339         return true;
340     }
341
342     // Expand our intrinsic height to encompass floats.
343     if (lowestFloatLogicalBottom() > (logicalHeight() - afterEdge) && createsBlockFormattingContext())
344         setLogicalHeight(lowestFloatLogicalBottom() + afterEdge);
345
346     if (isRenderMultiColumnBlock()) {
347         if (toRenderMultiColumnBlock(this)->shouldRelayoutMultiColumnBlock()) {
348             setChildNeedsLayout(MarkOnlyThis);
349             statePusher.pop();
350             return false;
351         }
352     } else if (hasColumns()) {
353         OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
354         if (childrenInline())
355             addOverflowFromInlineChildren();
356         else
357             addOverflowFromBlockChildren();
358         LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
359         m_overflow = savedOverflow.release();
360
361         if (!hasSpecifiedPageLogicalHeight && shouldRelayoutForPagination(pageLogicalHeight, layoutOverflowLogicalBottom)) {
362             statePusher.pop();
363             setEverHadLayout(true);
364             return false;
365         }
366
367         setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
368     }
369
370     if (shouldBreakAtLineToAvoidWidow()) {
371         statePusher.pop();
372         setEverHadLayout(true);
373         return false;
374     }
375
376     // Calculate our new height.
377     LayoutUnit oldHeight = logicalHeight();
378     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
379
380     if (isRenderFlowThread())
381         toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
382
383     updateLogicalHeight();
384     LayoutUnit newHeight = logicalHeight();
385     if (oldHeight != newHeight) {
386         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
387             // One of our children's floats may have become an overhanging float for us. We need to look for it.
388             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
389                 if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
390                     RenderBlockFlow* block = toRenderBlockFlow(child);
391                     if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
392                         addOverhangingFloats(block, false);
393                 }
394             }
395         }
396     }
397
398     bool heightChanged = (previousHeight != newHeight);
399     if (heightChanged)
400         relayoutChildren = true;
401
402     layoutPositionedObjects(relayoutChildren || isRoot());
403
404     updateRegionsAndShapesAfterChildLayout(flowThread, heightChanged);
405
406     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
407     computeOverflow(oldClientAfterEdge);
408
409     statePusher.pop();
410
411     fitBorderToLinesIfNeeded();
412
413     if (frameView()->partialLayout().isStopping())
414         return true;
415
416     if (renderView->layoutState()->m_pageLogicalHeight)
417         setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
418
419     updateLayerTransform();
420
421     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
422     // we overflow or not.
423     updateScrollInfoAfterLayout();
424
425     // Repaint with our new bounds if they are different from our old bounds.
426     bool didFullRepaint = repainter.repaintAfterLayout();
427     if (!didFullRepaint && m_repaintLogicalTop != m_repaintLogicalBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
428         if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
429             setShouldRepaintOverflowIfNeeded(true);
430         else
431             repaintOverflow();
432     }
433
434     clearNeedsLayout();
435     return true;
436 }
437
438 void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
439 {
440     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
441     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
442
443     // The child is a normal flow object. Compute the margins we will use for collapsing now.
444     child->computeAndSetBlockDirectionMargins(this);
445
446     // Try to guess our correct logical top position. In most cases this guess will
447     // be correct. Only if we're wrong (when we compute the real logical top position)
448     // will we have to potentially relayout.
449     LayoutUnit estimateWithoutPagination;
450     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
451
452     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
453     LayoutRect oldRect = child->frameRect();
454     LayoutUnit oldLogicalTop = logicalTopForChild(child);
455
456 #if !ASSERT_DISABLED
457     LayoutSize oldLayoutDelta = RuntimeEnabledFeatures::repaintAfterLayoutEnabled() ? LayoutSize() : view()->layoutDelta();
458 #endif
459     // Go ahead and position the child as though it didn't collapse with the top.
460     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
461
462     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
463     RenderBlockFlow* childRenderBlockFlow = (childRenderBlock && child->isRenderBlockFlow()) ? toRenderBlockFlow(child) : 0;
464     bool markDescendantsWithFloats = false;
465     if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats()) {
466         markDescendantsWithFloats = true;
467     } else if (UNLIKELY(logicalTopEstimate.mightBeSaturated())) {
468         // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
469         // very large elements. If it does the comparison with oldLogicalTop might yield a
470         // false negative as adding and removing margins, borders etc from a saturated number
471         // might yield incorrect results. If this is the case always mark for layout.
472         markDescendantsWithFloats = true;
473     } else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
474         // If an element might be affected by the presence of floats, then always mark it for
475         // layout.
476         LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
477         if (fb > logicalTopEstimate)
478             markDescendantsWithFloats = true;
479     }
480
481     if (childRenderBlockFlow) {
482         if (markDescendantsWithFloats)
483             childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
484         if (!child->isWritingModeRoot())
485             previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
486     }
487
488     SubtreeLayoutScope layoutScope(child);
489     if (!child->needsLayout())
490         child->markForPaginationRelayoutIfNeeded(layoutScope);
491
492     bool childHadLayout = child->everHadLayout();
493     bool childNeededLayout = child->needsLayout();
494     if (childNeededLayout)
495         child->layout();
496
497     if (frameView()->partialLayout().isStopping())
498         return;
499
500     // Cache if we are at the top of the block right now.
501     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
502     bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
503
504     // Now determine the correct ypos based off examination of collapsing margin
505     // values.
506     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo, childIsSelfCollapsing);
507
508     // Now check for clear.
509     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear, childIsSelfCollapsing);
510
511     bool paginated = view()->layoutState()->isPaginated();
512     if (paginated) {
513         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
514             atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
515     }
516
517     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
518
519     // Now we have a final top position. See if it really does end up being different from our estimate.
520     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
521     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
522     if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
523         SubtreeLayoutScope layoutScope(child);
524         if (child->shrinkToAvoidFloats()) {
525             // The child's width depends on the line width.
526             // When the child shifts to clear an item, its width can
527             // change (because it has more available line width).
528             // So go ahead and mark the item as dirty.
529             layoutScope.setChildNeedsLayout(child);
530         }
531
532         if (childRenderBlock) {
533             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
534                 childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
535             if (!child->needsLayout())
536                 child->markForPaginationRelayoutIfNeeded(layoutScope);
537         }
538
539         // Our guess was wrong. Make the child lay itself out again.
540         child->layoutIfNeeded();
541     }
542
543     // If we previously encountered a self-collapsing sibling of this child that had clearance then
544     // we set this bit to ensure we would not collapse the child's margins, and those of any subsequent
545     // self-collapsing siblings, with our parent. If this child is not self-collapsing then it can
546     // collapse its margins with the parent so reset the bit.
547     if (!marginInfo.canCollapseMarginAfterWithLastChild() && !childIsSelfCollapsing)
548         marginInfo.setCanCollapseMarginAfterWithLastChild(true);
549
550     // We are no longer at the top of the block if we encounter a non-empty child.
551     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
552     if (marginInfo.atBeforeSideOfBlock() && !childIsSelfCollapsing)
553         marginInfo.setAtBeforeSideOfBlock(false);
554
555     // Now place the child in the correct left position
556     determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
557
558     LayoutSize childOffset = child->location() - oldRect.location();
559     relayoutShapeDescendantIfMoved(childRenderBlock, childOffset);
560
561     // Update our height now that the child has been placed in the correct position.
562     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
563     if (mustSeparateMarginAfterForChild(child)) {
564         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
565         marginInfo.clearMargin();
566     }
567     // If the child has overhanging floats that intrude into following siblings (or possibly out
568     // of this block), then the parent gets notified of the floats now.
569     if (childRenderBlockFlow && childRenderBlockFlow->containsFloats())
570         maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(childRenderBlockFlow, !childNeededLayout));
571
572     if (childOffset.width() || childOffset.height()) {
573         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
574             view()->addLayoutDelta(childOffset);
575
576         // If the child moved, we have to repaint it as well as any floating/positioned
577         // descendants. An exception is if we need a layout. In this case, we know we're going to
578         // repaint ourselves (and the child) anyway.
579         if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && childHadLayout && !selfNeedsLayout())
580             child->repaintOverhangingFloats(true);
581         else if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
582             child->repaintDuringLayoutIfMoved(oldRect);
583     }
584
585     if (!childHadLayout && child->checkForRepaint()) {
586         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
587             child->repaint();
588         child->repaintOverhangingFloats(true);
589     }
590
591     if (paginated) {
592         // Check for an after page/column break.
593         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
594         if (newHeight != height())
595             setLogicalHeight(newHeight);
596     }
597
598     if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
599         ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
600     }
601 }
602
603 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
604 {
605     RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
606
607     if (estimateWithoutPagination != logicalTopAfterClear) {
608         // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
609         // position.
610         setLogicalHeight(logicalTopAfterClear);
611         setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
612
613         if (child->shrinkToAvoidFloats()) {
614             // The child's width depends on the line width.
615             // When the child shifts to clear an item, its width can
616             // change (because it has more available line width).
617             // So go ahead and mark the item as dirty.
618             child->setChildNeedsLayout(MarkOnlyThis);
619         }
620
621         SubtreeLayoutScope layoutScope(child);
622
623         if (childRenderBlock) {
624             if (!child->avoidsFloats() && childRenderBlock->containsFloats())
625                 toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
626             if (!child->needsLayout())
627                 child->markForPaginationRelayoutIfNeeded(layoutScope);
628         }
629
630         // Our guess was wrong. Make the child lay itself out again.
631         child->layoutIfNeeded();
632     }
633
634     LayoutUnit oldTop = logicalTopAfterClear;
635
636     // If the object has a page or column break value of "before", then we should shift to the top of the next page.
637     LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
638
639     if (pageLogicalHeightForOffset(result)) {
640         LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
641         LayoutUnit spaceShortage = child->logicalHeight() - remainingLogicalHeight;
642         if (spaceShortage > 0) {
643             // If the child crosses a column boundary, report a break, in case nothing inside it has already
644             // done so. The column balancer needs to know how much it has to stretch the columns to make more
645             // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
646             // This should be improved, though, because here we just pretend that the child is
647             // unsplittable. A splittable child, on the other hand, has break opportunities at every position
648             // where there's no child content, border or padding. In other words, we risk stretching more
649             // than necessary.
650             setPageBreak(result, spaceShortage);
651         }
652     }
653
654     // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
655     LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
656     LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
657
658     LayoutUnit paginationStrut = 0;
659     LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
660     if (unsplittableAdjustmentDelta)
661         paginationStrut = unsplittableAdjustmentDelta;
662     else if (childRenderBlock && childRenderBlock->paginationStrut())
663         paginationStrut = childRenderBlock->paginationStrut();
664
665     if (paginationStrut) {
666         // We are willing to propagate out to our parent block as long as we were at the top of the block prior
667         // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
668         if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
669             // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
670             // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
671             // and pushes to the next page anyway, so not too concerned about it.
672             setPaginationStrut(result + paginationStrut);
673             if (childRenderBlock)
674                 childRenderBlock->setPaginationStrut(0);
675         } else {
676             result += paginationStrut;
677         }
678     }
679
680     // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
681     setLogicalHeight(logicalHeight() + (result - oldTop));
682
683     // Return the final adjusted logical top.
684     return result;
685 }
686
687 void RenderBlockFlow::rebuildFloatsFromIntruding()
688 {
689     if (m_floatingObjects)
690         m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
691
692     HashSet<RenderBox*> oldIntrudingFloatSet;
693     if (!childrenInline() && m_floatingObjects) {
694         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
695         FloatingObjectSetIterator end = floatingObjectSet.end();
696         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
697             FloatingObject* floatingObject = *it;
698             if (!floatingObject->isDescendant())
699                 oldIntrudingFloatSet.add(floatingObject->renderer());
700         }
701     }
702
703     // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
704     if (avoidsFloats() || isRoot() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
705         if (m_floatingObjects) {
706             m_floatingObjects->clear();
707         }
708         if (!oldIntrudingFloatSet.isEmpty())
709             markAllDescendantsWithFloatsForLayout();
710         return;
711     }
712
713     RendererToFloatInfoMap floatMap;
714
715     if (m_floatingObjects) {
716         if (childrenInline())
717             m_floatingObjects->moveAllToFloatInfoMap(floatMap);
718         else
719             m_floatingObjects->clear();
720     }
721
722     // We should not process floats if the parent node is not a RenderBlockFlow. Otherwise, we will add
723     // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
724     // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
725     if (!parent() || !parent()->isRenderBlockFlow())
726         return;
727
728     // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
729     // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
730     // to avoid floats.
731     RenderBlockFlow* parentBlockFlow = toRenderBlockFlow(parent());
732     bool parentHasFloats = false;
733     RenderObject* prev = previousSibling();
734     while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
735         if (prev->isFloating())
736             parentHasFloats = true;
737         prev = prev->previousSibling();
738     }
739
740     // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
741     // them (as opposed to floats they contain themselves) so check for those here too.
742     LayoutUnit logicalTopOffset = logicalTop();
743     if (parentHasFloats || (prev && toRenderBlockFlow(prev)->isSelfCollapsingBlock() && parentBlockFlow->lowestFloatLogicalBottom() > logicalTopOffset))
744         addIntrudingFloats(parentBlockFlow, parentBlockFlow->logicalLeftOffsetForContent(), logicalTopOffset);
745
746     LayoutUnit logicalLeftOffset = 0;
747     if (prev) {
748         logicalTopOffset -= toRenderBox(prev)->logicalTop();
749     } else {
750         prev = parentBlockFlow;
751         logicalLeftOffset += parentBlockFlow->logicalLeftOffsetForContent();
752     }
753
754     // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
755     RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
756     if (blockFlow->m_floatingObjects && blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
757         addIntrudingFloats(blockFlow, logicalLeftOffset, logicalTopOffset);
758
759     if (childrenInline()) {
760         LayoutUnit changeLogicalTop = LayoutUnit::max();
761         LayoutUnit changeLogicalBottom = LayoutUnit::min();
762         if (m_floatingObjects) {
763             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
764             FloatingObjectSetIterator end = floatingObjectSet.end();
765             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
766                 FloatingObject* floatingObject = *it;
767                 FloatingObject* oldFloatingObject = floatMap.get(floatingObject->renderer());
768                 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
769                 if (oldFloatingObject) {
770                     LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
771                     if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject)) {
772                         changeLogicalTop = 0;
773                         changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
774                     } else {
775                         if (logicalBottom != oldLogicalBottom) {
776                             changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
777                             changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
778                         }
779                         LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
780                         LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
781                         if (logicalTop != oldLogicalTop) {
782                             changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
783                             changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
784                         }
785                     }
786
787                     floatMap.remove(floatingObject->renderer());
788                     if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
789                         ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
790                         oldFloatingObject->originatingLine()->markDirty();
791                     }
792                     delete oldFloatingObject;
793                 } else {
794                     changeLogicalTop = 0;
795                     changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
796                 }
797             }
798         }
799
800         RendererToFloatInfoMap::iterator end = floatMap.end();
801         for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
802             FloatingObject* floatingObject = (*it).value;
803             if (!floatingObject->isDescendant()) {
804                 changeLogicalTop = 0;
805                 changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
806             }
807         }
808         deleteAllValues(floatMap);
809
810         markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
811     } else if (!oldIntrudingFloatSet.isEmpty()) {
812         // If there are previously intruding floats that no longer intrude, then children with floats
813         // should also get layout because they might need their floating object lists cleared.
814         if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size()) {
815             markAllDescendantsWithFloatsForLayout();
816         } else {
817             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
818             FloatingObjectSetIterator end = floatingObjectSet.end();
819             for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
820                 oldIntrudingFloatSet.remove((*it)->renderer());
821             if (!oldIntrudingFloatSet.isEmpty())
822                 markAllDescendantsWithFloatsForLayout();
823         }
824     }
825 }
826
827 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope& layoutScope, LayoutUnit beforeEdge, LayoutUnit afterEdge)
828 {
829     dirtyForLayoutFromPercentageHeightDescendants(layoutScope);
830
831     // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
832     MarginInfo marginInfo(this, beforeEdge, afterEdge);
833
834     // Fieldsets need to find their legend and position it inside the border of the object.
835     // The legend then gets skipped during normal layout. The same is true for ruby text.
836     // It doesn't get included in the normal layout process but is instead skipped.
837     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren, layoutScope);
838
839     LayoutUnit previousFloatLogicalBottom = 0;
840     maxFloatLogicalBottom = 0;
841
842     RenderBox* next = firstChildBox();
843     RenderBox* lastNormalFlowChild = 0;
844
845     while (next) {
846         RenderBox* child = next;
847         next = child->nextSiblingBox();
848
849         LayoutRectRecorder recorder(*child);
850
851         if (childToExclude == child)
852             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
853
854         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
855
856         if (child->isOutOfFlowPositioned()) {
857             child->containingBlock()->insertPositionedObject(child);
858             adjustPositionedBlock(child, marginInfo);
859             continue;
860         }
861         if (child->isFloating()) {
862             insertFloatingObject(child);
863             adjustFloatingBlock(marginInfo);
864             continue;
865         }
866
867         // Lay out the child.
868         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
869         lastNormalFlowChild = child;
870
871         // If doing a partial layout and the child was the target renderer, early exit here.
872         if (frameView()->partialLayout().checkPartialLayoutComplete(child))
873             return;
874
875     }
876
877     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
878     // determining the correct collapsed bottom margin information.
879     handleAfterSideOfBlock(lastNormalFlowChild, beforeEdge, afterEdge, marginInfo);
880 }
881
882 // Our MarginInfo state used when laying out block children.
883 MarginInfo::MarginInfo(RenderBlockFlow* blockFlow, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
884     : m_canCollapseMarginAfterWithLastChild(true)
885     , m_atBeforeSideOfBlock(true)
886     , m_atAfterSideOfBlock(false)
887     , m_hasMarginBeforeQuirk(false)
888     , m_hasMarginAfterQuirk(false)
889     , m_determinedMarginBeforeQuirk(false)
890     , m_discardMargin(false)
891 {
892     RenderStyle* blockStyle = blockFlow->style();
893     ASSERT(blockFlow->isRenderView() || blockFlow->parent());
894     m_canCollapseWithChildren = !blockFlow->createsBlockFormattingContext() && !blockFlow->isRenderFlowThread() && !blockFlow->isRenderView();
895
896     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
897
898     // If any height other than auto is specified in CSS, then we don't collapse our bottom
899     // margins with our children's margins. To do otherwise would be to risk odd visual
900     // effects when the children overflow out of the parent block and yet still collapse
901     // with it. We also don't collapse if we have any bottom border/padding.
902     m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
903         && (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
904
905     m_quirkContainer = blockFlow->isTableCell() || blockFlow->isBody();
906
907     m_discardMargin = m_canCollapseMarginBeforeWithChildren && blockFlow->mustDiscardMarginBefore();
908
909     m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxPositiveMarginBefore() : LayoutUnit();
910     m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !blockFlow->mustDiscardMarginBefore()) ? blockFlow->maxNegativeMarginBefore() : LayoutUnit();
911 }
912
913 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox* child) const
914 {
915     LayoutUnit childBeforePositive = 0;
916     LayoutUnit childBeforeNegative = 0;
917     LayoutUnit childAfterPositive = 0;
918     LayoutUnit childAfterNegative = 0;
919
920     LayoutUnit beforeMargin = 0;
921     LayoutUnit afterMargin = 0;
922
923     RenderBlockFlow* childRenderBlockFlow = child->isRenderBlockFlow() ? toRenderBlockFlow(child) : 0;
924
925     // If the child has the same directionality as we do, then we can just return its
926     // margins in the same direction.
927     if (!child->isWritingModeRoot()) {
928         if (childRenderBlockFlow) {
929             childBeforePositive = childRenderBlockFlow->maxPositiveMarginBefore();
930             childBeforeNegative = childRenderBlockFlow->maxNegativeMarginBefore();
931             childAfterPositive = childRenderBlockFlow->maxPositiveMarginAfter();
932             childAfterNegative = childRenderBlockFlow->maxNegativeMarginAfter();
933         } else {
934             beforeMargin = child->marginBefore();
935             afterMargin = child->marginAfter();
936         }
937     } else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
938         // The child has a different directionality. If the child is parallel, then it's just
939         // flipped relative to us. We can use the margins for the opposite edges.
940         if (childRenderBlockFlow) {
941             childBeforePositive = childRenderBlockFlow->maxPositiveMarginAfter();
942             childBeforeNegative = childRenderBlockFlow->maxNegativeMarginAfter();
943             childAfterPositive = childRenderBlockFlow->maxPositiveMarginBefore();
944             childAfterNegative = childRenderBlockFlow->maxNegativeMarginBefore();
945         } else {
946             beforeMargin = child->marginAfter();
947             afterMargin = child->marginBefore();
948         }
949     } else {
950         // The child is perpendicular to us, which means its margins don't collapse but are on the
951         // "logical left/right" sides of the child box. We can just return the raw margin in this case.
952         beforeMargin = marginBeforeForChild(child);
953         afterMargin = marginAfterForChild(child);
954     }
955
956     // Resolve uncollapsing margins into their positive/negative buckets.
957     if (beforeMargin) {
958         if (beforeMargin > 0)
959             childBeforePositive = beforeMargin;
960         else
961             childBeforeNegative = -beforeMargin;
962     }
963     if (afterMargin) {
964         if (afterMargin > 0)
965             childAfterPositive = afterMargin;
966         else
967             childAfterNegative = -afterMargin;
968     }
969
970     return RenderBlockFlow::MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
971 }
972
973 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& marginInfo, bool childIsSelfCollapsing)
974 {
975     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
976     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
977
978     // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
979     childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
980
981     // Get the four margin values for the child and cache them.
982     const RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
983
984     // Get our max pos and neg top margins.
985     LayoutUnit posTop = childMargins.positiveMarginBefore();
986     LayoutUnit negTop = childMargins.negativeMarginBefore();
987
988     // For self-collapsing blocks, collapse our bottom margins into our
989     // top to get new posTop and negTop values.
990     if (childIsSelfCollapsing) {
991         posTop = max(posTop, childMargins.positiveMarginAfter());
992         negTop = max(negTop, childMargins.negativeMarginAfter());
993     }
994
995     // See if the top margin is quirky. We only care if this child has
996     // margins that will collapse with us.
997     bool topQuirk = hasMarginBeforeQuirk(child);
998
999     if (marginInfo.canCollapseWithMarginBefore()) {
1000         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1001             // This child is collapsing with the top of the
1002             // block. If it has larger margin values, then we need to update
1003             // our own maximal values.
1004             if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
1005                 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
1006
1007             // The minute any of the margins involved isn't a quirk, don't
1008             // collapse it away, even if the margin is smaller (www.webreference.com
1009             // has an example of this, a <dt> with 0.8em author-specified inside
1010             // a <dl> inside a <td>.
1011             if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
1012                 setHasMarginBeforeQuirk(false);
1013                 marginInfo.setDeterminedMarginBeforeQuirk(true);
1014             }
1015
1016             if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore()) {
1017                 // We have no top margin and our top child has a quirky margin.
1018                 // We will pick up this quirky margin and pass it through.
1019                 // This deals with the <td><div><p> case.
1020                 // Don't do this for a block that split two inlines though. You do
1021                 // still apply margins in this case.
1022                 setHasMarginBeforeQuirk(true);
1023             }
1024         } else {
1025             // The before margin of the container will also discard all the margins it is collapsing with.
1026             setMustDiscardMarginBefore();
1027         }
1028     }
1029
1030     // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
1031     if (childDiscardMarginBefore) {
1032         marginInfo.setDiscardMargin(true);
1033         marginInfo.clearMargin();
1034     }
1035
1036     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
1037         marginInfo.setHasMarginBeforeQuirk(topQuirk);
1038
1039     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
1040     LayoutUnit logicalTop = beforeCollapseLogicalTop;
1041
1042     LayoutUnit clearanceForSelfCollapsingBlock;
1043     RenderObject* prev = child->previousSibling();
1044     RenderBlockFlow* previousBlockFlow =  prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned() ? toRenderBlockFlow(prev) : 0;
1045     // 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
1046     // 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
1047     // 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.
1048     if (!marginInfo.canCollapseWithMarginBefore() && previousBlockFlow && previousBlockFlow->isSelfCollapsingBlock()) {
1049         clearanceForSelfCollapsingBlock = previousBlockFlow->marginOffsetForSelfCollapsingBlock();
1050         setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
1051     }
1052
1053     if (childIsSelfCollapsing) {
1054         // 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.
1055         // Also, the child's top position equals the logical height of the container.
1056         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
1057             // This child has no height. We need to compute our
1058             // position before we collapse the child's margins together,
1059             // so that we can get an accurate position for the zero-height block.
1060             LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
1061             LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
1062             marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
1063
1064             // Now collapse the child's margins together, which means examining our
1065             // bottom margin values as well.
1066             marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
1067             marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
1068
1069             if (!marginInfo.canCollapseWithMarginBefore()) {
1070                 // We need to make sure that the position of the self-collapsing block
1071                 // is correct, since it could have overflowing content
1072                 // that needs to be positioned correctly (e.g., a block that
1073                 // had a specified height of 0 but that actually had subcontent).
1074                 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
1075             }
1076         }
1077     } else {
1078         if (mustSeparateMarginBeforeForChild(child)) {
1079             ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
1080             // If we are at the before side of the block and we collapse, ignore the computed margin
1081             // and just add the child margin to the container height. This will correctly position
1082             // the child inside the container.
1083             LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
1084             setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
1085             logicalTop = logicalHeight();
1086         } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
1087             || (!marginInfo.canCollapseMarginBeforeWithChildren()
1088             && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
1089             // We're collapsing with a previous sibling's margins and not
1090             // with the top of the block.
1091             setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
1092             logicalTop = logicalHeight();
1093         }
1094
1095         marginInfo.setDiscardMargin(childDiscardMarginAfter);
1096
1097         if (!marginInfo.discardMargin()) {
1098             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
1099             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
1100         } else {
1101             marginInfo.clearMargin();
1102         }
1103
1104         if (marginInfo.margin())
1105             marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
1106     }
1107
1108     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
1109     // collapsed into the page edge.
1110     LayoutState* layoutState = view()->layoutState();
1111     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop) {
1112         LayoutUnit oldLogicalTop = logicalTop;
1113         logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
1114         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
1115     }
1116
1117     if (previousBlockFlow) {
1118         // 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
1119         // any floats from the parent will now overhang.
1120         LayoutUnit oldLogicalHeight = logicalHeight();
1121         setLogicalHeight(logicalTop);
1122         if (previousBlockFlow->containsFloats() && !previousBlockFlow->avoidsFloats() && (previousBlockFlow->logicalTop() + previousBlockFlow->lowestFloatLogicalBottom()) > logicalTop)
1123             addOverhangingFloats(previousBlockFlow, false);
1124         setLogicalHeight(oldLogicalHeight);
1125
1126         // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
1127         // 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
1128         // floats in the parent that overhang |child|'s new logical top.
1129         bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
1130         if (logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1131             child->setNeedsLayout();
1132     }
1133
1134     return logicalTop;
1135 }
1136
1137 void RenderBlockFlow::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1138 {
1139     bool isHorizontal = isHorizontalWritingMode();
1140     bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1141
1142     LayoutUnit logicalTop = logicalHeight();
1143     updateStaticInlinePositionForChild(child, logicalTop);
1144
1145     if (!marginInfo.canCollapseWithMarginBefore()) {
1146         // Positioned blocks don't collapse margins, so add the margin provided by
1147         // the container now. The child's own margin is added later when calculating its logical top.
1148         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1149         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1150         logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1151     }
1152
1153     RenderLayer* childLayer = child->layer();
1154     if (childLayer->staticBlockPosition() != logicalTop) {
1155         childLayer->setStaticBlockPosition(logicalTop);
1156         if (hasStaticBlockPosition)
1157             child->setChildNeedsLayout(MarkOnlyThis);
1158     }
1159 }
1160
1161 LayoutUnit RenderBlockFlow::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart)
1162 {
1163     LayoutUnit startPosition = startOffsetForContent();
1164
1165     // Add in our start margin.
1166     LayoutUnit oldPosition = startPosition + childMarginStart;
1167     LayoutUnit newPosition = oldPosition;
1168
1169     LayoutUnit blockOffset = logicalTopForChild(child);
1170     LayoutUnit startOff = startOffsetForLine(blockOffset, false, logicalHeightForChild(child));
1171
1172     if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
1173         if (childMarginStart < 0)
1174             startOff += childMarginStart;
1175         newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
1176     } else if (startOff != startPosition) {
1177         newPosition = startOff + childMarginStart;
1178     }
1179
1180     return newPosition - oldPosition;
1181 }
1182
1183 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos, bool childIsSelfCollapsing)
1184 {
1185     LayoutUnit heightIncrease = getClearDelta(child, yPos);
1186     if (!heightIncrease)
1187         return yPos;
1188
1189     if (childIsSelfCollapsing) {
1190         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
1191
1192         // For self-collapsing blocks that clear, they can still collapse their
1193         // margins with following siblings. Reset the current margins to represent
1194         // the self-collapsing block's margins only.
1195         // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
1196         RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
1197         if (!childDiscardMargin) {
1198             marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
1199             marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
1200         } else {
1201             marginInfo.clearMargin();
1202         }
1203         marginInfo.setDiscardMargin(childDiscardMargin);
1204
1205         // CSS2.1 states:
1206         // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
1207         // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
1208         // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Set a bit to ensure
1209         // this happens; it will get reset if we encounter an in-flow sibling that is not self-collapsing.
1210         marginInfo.setCanCollapseMarginAfterWithLastChild(false);
1211
1212         // 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
1213         // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
1214         // 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
1215         // margins can collapse at the correct vertical position.
1216         // 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
1217         // (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],
1218         // i.e., clearance = [height of float] - margin-top".
1219         setLogicalHeight(child->logicalTop() + childMargins.negativeMarginBefore());
1220     } else {
1221         // Increase our height by the amount we had to clear.
1222         setLogicalHeight(logicalHeight() + heightIncrease);
1223     }
1224
1225     if (marginInfo.canCollapseWithMarginBefore()) {
1226         // We can no longer collapse with the top of the block since a clear
1227         // occurred. The empty blocks collapse into the cleared block.
1228         // FIXME: This isn't quite correct. Need clarification for what to do
1229         // if the height the cleared block is offset by is smaller than the
1230         // margins involved.
1231         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1232         marginInfo.setAtBeforeSideOfBlock(false);
1233
1234         // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1235         setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
1236     }
1237
1238     return yPos + heightIncrease;
1239 }
1240
1241 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1242 {
1243     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1244         // 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.
1245         // Don't update the max margin values because we won't need them anyway.
1246         if (marginInfo.discardMargin()) {
1247             setMustDiscardMarginAfter();
1248             return;
1249         }
1250
1251         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1252         // with our children.
1253         setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1254
1255         if (!marginInfo.hasMarginAfterQuirk())
1256             setHasMarginAfterQuirk(false);
1257
1258         if (marginInfo.hasMarginAfterQuirk() && !marginAfter()) {
1259             // We have no bottom margin and our last child has a quirky margin.
1260             // We will pick up this quirky margin and pass it through.
1261             // This deals with the <td><div><p> case.
1262             setHasMarginAfterQuirk(true);
1263         }
1264     }
1265 }
1266
1267 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1268 {
1269     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1270     // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1271     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1272     if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
1273         return;
1274
1275     // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1276     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1277     if (child->style()->marginBeforeCollapse() == MDISCARD) {
1278         positiveMarginBefore = 0;
1279         negativeMarginBefore = 0;
1280         discardMarginBefore = true;
1281         return;
1282     }
1283
1284     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1285     positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
1286     negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
1287
1288     if (!child->isRenderBlockFlow())
1289         return;
1290
1291     RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1292     if (childBlockFlow->childrenInline() || childBlockFlow->isWritingModeRoot())
1293         return;
1294
1295     MarginInfo childMarginInfo(childBlockFlow, childBlockFlow->borderBefore() + childBlockFlow->paddingBefore(), childBlockFlow->borderAfter() + childBlockFlow->paddingAfter());
1296     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1297         return;
1298
1299     RenderBox* grandchildBox = childBlockFlow->firstChildBox();
1300     for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1301         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1302             break;
1303     }
1304
1305     // Give up if there is clearance on the box, since it probably won't collapse into us.
1306     if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
1307         return;
1308
1309     // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1310     if (grandchildBox->needsLayout()) {
1311         grandchildBox->computeAndSetBlockDirectionMargins(this);
1312         if (grandchildBox->isRenderBlock()) {
1313             RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
1314             grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
1315             grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
1316         }
1317     }
1318
1319     // Collapse the margin of the grandchild box with our own to produce an estimate.
1320     childBlockFlow->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1321 }
1322
1323 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1324 {
1325     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1326     // relayout if there are intruding floats.
1327     LayoutUnit logicalTopEstimate = logicalHeight();
1328     if (!marginInfo.canCollapseWithMarginBefore()) {
1329         LayoutUnit positiveMarginBefore = 0;
1330         LayoutUnit negativeMarginBefore = 0;
1331         bool discardMarginBefore = false;
1332         if (child->selfNeedsLayout()) {
1333             // Try to do a basic estimation of how the collapse is going to go.
1334             marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1335         } else {
1336             // Use the cached collapsed margin values from a previous layout. Most of the time they
1337             // will be right.
1338             RenderBlockFlow::MarginValues marginValues = marginValuesForChild(child);
1339             positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
1340             negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
1341             discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1342         }
1343
1344         // Collapse the result with our current margins.
1345         if (!discardMarginBefore)
1346             logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
1347     }
1348
1349     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1350     // page.
1351     LayoutState* layoutState = view()->layoutState();
1352     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight())
1353         logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1354
1355     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1356
1357     estimateWithoutPagination = logicalTopEstimate;
1358
1359     if (layoutState->isPaginated()) {
1360         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1361         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1362
1363         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1364         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1365
1366         if (!child->selfNeedsLayout() && child->isRenderBlock())
1367             logicalTopEstimate += toRenderBlock(child)->paginationStrut();
1368     }
1369
1370     return logicalTopEstimate;
1371 }
1372
1373 LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
1374 {
1375     ASSERT(isSelfCollapsingBlock());
1376     RenderBlockFlow* parentBlock = toRenderBlockFlow(parent());
1377     if (parentBlock && style()->clear() && parentBlock->getClearDelta(this, logicalHeight()))
1378         return marginValuesForChild(this).positiveMarginBefore();
1379     return LayoutUnit();
1380 }
1381
1382 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
1383 {
1384     // The float should be positioned taking into account the bottom margin
1385     // of the previous flow. We add that margin into the height, get the
1386     // float positioned properly, and then subtract the margin out of the
1387     // height again. In the case of self-collapsing blocks, we always just
1388     // use the top margins, since the self-collapsing block collapsed its
1389     // own bottom margin into its top margin.
1390     //
1391     // Note also that the previous flow may collapse its margin into the top of
1392     // our block. If this is the case, then we do not add the margin in to our
1393     // height when computing the position of the float. This condition can be tested
1394     // for by simply calling canCollapseWithMarginBefore. See
1395     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1396     // an example of this scenario.
1397     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1398     setLogicalHeight(logicalHeight() + marginOffset);
1399     positionNewFloats();
1400     setLogicalHeight(logicalHeight() - marginOffset);
1401 }
1402
1403 void RenderBlockFlow::handleAfterSideOfBlock(RenderBox* lastChild, LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1404 {
1405     marginInfo.setAtAfterSideOfBlock(true);
1406
1407     // If our last child was a self-collapsing block with clearance then our logical height is flush with the
1408     // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
1409     // to perform now is at the child's margin-top - so adjust our height to that position.
1410     if (lastChild && lastChild->isRenderBlockFlow() && lastChild->isSelfCollapsingBlock())
1411         setLogicalHeight(logicalHeight() - toRenderBlockFlow(lastChild)->marginOffsetForSelfCollapsingBlock());
1412
1413     if (marginInfo.canCollapseMarginAfterWithChildren() && !marginInfo.canCollapseMarginAfterWithLastChild())
1414         marginInfo.setCanCollapseMarginAfterWithChildren(false);
1415
1416     // If we can't collapse with children then go ahead and add in the bottom margin.
1417     if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1418         && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1419         setLogicalHeight(logicalHeight() + marginInfo.margin());
1420
1421     // Now add in our bottom border/padding.
1422     setLogicalHeight(logicalHeight() + afterSide);
1423
1424     // Negative margins can cause our height to shrink below our minimal height (border/padding).
1425     // If this happens, ensure that the computed height is increased to the minimal height.
1426     setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
1427
1428     // Update our bottom collapsed margin info.
1429     setCollapsedBottomMargin(marginInfo);
1430 }
1431
1432 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1433 {
1434     if (style()->marginBeforeCollapse() == MDISCARD) {
1435         ASSERT(value);
1436         return;
1437     }
1438
1439     if (!m_rareData && !value)
1440         return;
1441
1442     if (!m_rareData)
1443         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1444
1445     m_rareData->m_discardMarginBefore = value;
1446 }
1447
1448 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1449 {
1450     if (style()->marginAfterCollapse() == MDISCARD) {
1451         ASSERT(value);
1452         return;
1453     }
1454
1455     if (!m_rareData && !value)
1456         return;
1457
1458     if (!m_rareData)
1459         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1460
1461     m_rareData->m_discardMarginAfter = value;
1462 }
1463
1464 bool RenderBlockFlow::mustDiscardMarginBefore() const
1465 {
1466     return style()->marginBeforeCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginBefore);
1467 }
1468
1469 bool RenderBlockFlow::mustDiscardMarginAfter() const
1470 {
1471     return style()->marginAfterCollapse() == MDISCARD || (m_rareData && m_rareData->m_discardMarginAfter);
1472 }
1473
1474 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox* child) const
1475 {
1476     ASSERT(!child->selfNeedsLayout());
1477     if (!child->isWritingModeRoot())
1478         return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1479     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1480         return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1481
1482     // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1483     // In case the boxes are perpendicular we assume the property is not specified.
1484     return false;
1485 }
1486
1487 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox* child) const
1488 {
1489     ASSERT(!child->selfNeedsLayout());
1490     if (!child->isWritingModeRoot())
1491         return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginAfter() : (child->style()->marginAfterCollapse() == MDISCARD);
1492     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1493         return child->isRenderBlockFlow() ? toRenderBlockFlow(child)->mustDiscardMarginBefore() : (child->style()->marginBeforeCollapse() == MDISCARD);
1494
1495     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1496     return false;
1497 }
1498
1499 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1500 {
1501     if (!m_rareData) {
1502         if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(this))
1503             return;
1504         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1505     }
1506     m_rareData->m_margins.setPositiveMarginBefore(pos);
1507     m_rareData->m_margins.setNegativeMarginBefore(neg);
1508 }
1509
1510 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1511 {
1512     if (!m_rareData) {
1513         if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(this))
1514             return;
1515         m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
1516     }
1517     m_rareData->m_margins.setPositiveMarginAfter(pos);
1518     m_rareData->m_margins.setNegativeMarginAfter(neg);
1519 }
1520
1521 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox* child) const
1522 {
1523     ASSERT(!child->selfNeedsLayout());
1524     const RenderStyle* childStyle = child->style();
1525     if (!child->isWritingModeRoot())
1526         return childStyle->marginBeforeCollapse() == MSEPARATE;
1527     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1528         return childStyle->marginAfterCollapse() == MSEPARATE;
1529
1530     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1531     return false;
1532 }
1533
1534 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox* child) const
1535 {
1536     ASSERT(!child->selfNeedsLayout());
1537     const RenderStyle* childStyle = child->style();
1538     if (!child->isWritingModeRoot())
1539         return childStyle->marginAfterCollapse() == MSEPARATE;
1540     if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
1541         return childStyle->marginBeforeCollapse() == MSEPARATE;
1542
1543     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1544     return false;
1545 }
1546
1547 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
1548 {
1549     // FIXME: Add page break checking here when we support printing.
1550     RenderFlowThread* flowThread = flowThreadContainingBlock();
1551     bool isInsideMulticolFlowThread = flowThread;
1552     bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1553     bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1554     bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS)
1555         || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS);
1556     if (checkBeforeAlways && inNormalFlow(child)) {
1557         if (checkColumnBreaks) {
1558             if (isInsideMulticolFlowThread) {
1559                 LayoutUnit offsetBreakAdjustment = 0;
1560                 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset, child, true, &offsetBreakAdjustment))
1561                     return logicalOffset + offsetBreakAdjustment;
1562             } else {
1563                 view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
1564             }
1565         }
1566         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1567     }
1568     return logicalOffset;
1569 }
1570
1571 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1572 {
1573     // FIXME: Add page break checking here when we support printing.
1574     RenderFlowThread* flowThread = flowThreadContainingBlock();
1575     bool isInsideMulticolFlowThread = flowThread;
1576     bool checkColumnBreaks = isInsideMulticolFlowThread || view()->layoutState()->isPaginatingColumns();
1577     bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1578     bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS)
1579         || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS);
1580     if (checkAfterAlways && inNormalFlow(child)) {
1581         LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1582
1583         // So our margin doesn't participate in the next collapsing steps.
1584         marginInfo.clearMargin();
1585
1586         if (checkColumnBreaks) {
1587             if (isInsideMulticolFlowThread) {
1588                 LayoutUnit offsetBreakAdjustment = 0;
1589                 if (flowThread->addForcedRegionBreak(offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, child, false, &offsetBreakAdjustment))
1590                     return logicalOffset + marginOffset + offsetBreakAdjustment;
1591             } else {
1592                 view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
1593             }
1594         }
1595         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1596     }
1597     return logicalOffset;
1598 }
1599
1600 void RenderBlockFlow::addOverflowFromFloats()
1601 {
1602     if (!m_floatingObjects)
1603         return;
1604
1605     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1606     FloatingObjectSetIterator end = floatingObjectSet.end();
1607     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1608         FloatingObject* floatingObject = *it;
1609         if (floatingObject->isDescendant())
1610             addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
1611     }
1612 }
1613
1614 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1615 {
1616     RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
1617     if (!hasColumns() && (recomputeFloats || createsBlockFormattingContext() || hasSelfPaintingLayer()))
1618         addOverflowFromFloats();
1619 }
1620
1621 RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
1622 {
1623     RootInlineBox* rootBox = createRootInlineBox();
1624     m_lineBoxes.appendLineBox(rootBox);
1625
1626     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1627         if (AXObjectCache* cache = document().existingAXObjectCache())
1628             cache->recomputeIsIgnored(this);
1629     }
1630
1631     return rootBox;
1632 }
1633
1634 void RenderBlockFlow::deleteLineBoxTree()
1635 {
1636     if (containsFloats())
1637         m_floatingObjects->clearLineBoxTreePointers();
1638     RenderBlock::deleteLineBoxTree();
1639 }
1640
1641 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
1642 {
1643     if (!everHadLayout() && !containsFloats())
1644         return;
1645
1646     MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
1647     setChildNeedsLayout(markParents);
1648
1649     if (floatToRemove)
1650         removeFloatingObject(floatToRemove);
1651
1652     // Iterate over our children and mark them as needed.
1653     if (!childrenInline()) {
1654         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1655             if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
1656                 continue;
1657             if (!child->isRenderBlockFlow()) {
1658                 RenderBlock* childBlock = toRenderBlock(child);
1659                 if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
1660                     childBlock->setChildNeedsLayout(markParents);
1661                 continue;
1662             }
1663             RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
1664             if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
1665                 childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
1666         }
1667     }
1668 }
1669
1670 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
1671 {
1672     if (!m_floatingObjects)
1673         return;
1674
1675     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1676     FloatingObjectSetIterator end = floatingObjectSet.end();
1677
1678     for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
1679         if (!next->isRenderBlockFlow() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
1680             continue;
1681
1682         RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1683         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1684             RenderBox* floatingBox = (*it)->renderer();
1685             if (floatToRemove && floatingBox != floatToRemove)
1686                 continue;
1687             if (nextBlock->containsFloat(floatingBox))
1688                 nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
1689         }
1690     }
1691 }
1692
1693 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
1694 {
1695     // There is no need to compute clearance if we have no floats.
1696     if (!containsFloats())
1697         return 0;
1698
1699     // At least one float is present. We need to perform the clearance computation.
1700     bool clearSet = child->style()->clear() != CNONE;
1701     LayoutUnit logicalBottom = 0;
1702     switch (child->style()->clear()) {
1703     case CNONE:
1704         break;
1705     case CLEFT:
1706         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
1707         break;
1708     case CRIGHT:
1709         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
1710         break;
1711     case CBOTH:
1712         logicalBottom = lowestFloatLogicalBottom();
1713         break;
1714     }
1715
1716     // 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).
1717     LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
1718     if (!result && child->avoidsFloats()) {
1719         LayoutUnit newLogicalTop = logicalTop;
1720         while (true) {
1721             LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
1722             if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent())
1723                 return newLogicalTop - logicalTop;
1724
1725             LayoutRect borderBox = child->borderBoxRect();
1726             LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1727
1728             // FIXME: None of this is right for perpendicular writing-mode children.
1729             LayoutUnit childOldLogicalWidth = child->logicalWidth();
1730             LayoutUnit childOldMarginLeft = child->marginLeft();
1731             LayoutUnit childOldMarginRight = child->marginRight();
1732             LayoutUnit childOldLogicalTop = child->logicalTop();
1733
1734             child->setLogicalTop(newLogicalTop);
1735             child->updateLogicalWidth();
1736             borderBox = child->borderBoxRect();
1737             LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
1738
1739             child->setLogicalTop(childOldLogicalTop);
1740             child->setLogicalWidth(childOldLogicalWidth);
1741             child->setMarginLeft(childOldMarginLeft);
1742             child->setMarginRight(childOldMarginRight);
1743
1744             if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
1745                 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
1746                 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
1747                 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
1748                 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
1749                     child->setChildNeedsLayout(MarkOnlyThis);
1750                 return newLogicalTop - logicalTop;
1751             }
1752
1753             newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
1754             ASSERT(newLogicalTop >= logicalTop);
1755             if (newLogicalTop < logicalTop)
1756                 break;
1757         }
1758         ASSERT_NOT_REACHED();
1759     }
1760     return result;
1761 }
1762
1763 void RenderBlockFlow::createFloatingObjects()
1764 {
1765     m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
1766 }
1767
1768 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
1769 {
1770     RenderStyle* oldStyle = style();
1771     s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
1772     if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()
1773         && containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
1774             markAllDescendantsWithFloatsForLayout();
1775
1776     RenderBlock::styleWillChange(diff, newStyle);
1777 }
1778
1779 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1780 {
1781     RenderBlock::styleDidChange(diff, oldStyle);
1782
1783     // After our style changed, if we lose our ability to propagate floats into next sibling
1784     // blocks, then we need to find the top most parent containing that overhanging float and
1785     // then mark its descendants with floats for layout and clear all floats from its next
1786     // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
1787     bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
1788     if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
1789         RenderBlockFlow* parentBlockFlow = this;
1790         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1791         FloatingObjectSetIterator end = floatingObjectSet.end();
1792
1793         for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
1794             if (curr->isRenderBlockFlow()) {
1795                 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
1796
1797                 if (currBlock->hasOverhangingFloats()) {
1798                     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1799                         RenderBox* renderer = (*it)->renderer();
1800                         if (currBlock->hasOverhangingFloat(renderer)) {
1801                             parentBlockFlow = currBlock;
1802                             break;
1803                         }
1804                     }
1805                 }
1806             }
1807         }
1808
1809         parentBlockFlow->markAllDescendantsWithFloatsForLayout();
1810         parentBlockFlow->markSiblingsWithFloatsForLayout();
1811     }
1812 }
1813
1814 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
1815 {
1816     if (child->style()->isOriginalDisplayInlineType())
1817         setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
1818     else
1819         setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent());
1820 }
1821
1822 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
1823 {
1824     child->layer()->setStaticInlinePosition(inlinePosition);
1825 }
1826
1827 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1828 {
1829     RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
1830     moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
1831
1832     // When a portion of the render tree is being detached, anonymous blocks
1833     // will be combined as their children are deleted. In this process, the
1834     // anonymous block later in the tree is merged into the one preceeding it.
1835     // It can happen that the later block (this) contains floats that the
1836     // previous block (toBlockFlow) did not contain, and thus are not in the
1837     // floating objects list for toBlockFlow. This can result in toBlockFlow containing
1838     // floats that are not in it's floating objects list, but are in the
1839     // floating objects lists of siblings and parents. This can cause problems
1840     // when the float itself is deleted, since the deletion code assumes that
1841     // if a float is not in it's containing block's floating objects list, it
1842     // isn't in any floating objects list. In order to preserve this condition
1843     // (removing it has serious performance implications), we need to copy the
1844     // floating objects from the old block (this) to the new block (toBlockFlow).
1845     // The float's metrics will likely all be wrong, but since toBlockFlow is
1846     // already marked for layout, this will get fixed before anything gets
1847     // displayed.
1848     // See bug https://code.google.com/p/chromium/issues/detail?id=230907
1849     if (m_floatingObjects) {
1850         if (!toBlockFlow->m_floatingObjects)
1851             toBlockFlow->createFloatingObjects();
1852
1853         const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1854         FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1855
1856         for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1857             FloatingObject* floatingObject = *it;
1858
1859             // Don't insert the object again if it's already in the list
1860             if (toBlockFlow->containsFloat(floatingObject->renderer()))
1861                 continue;
1862
1863             toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
1864         }
1865     }
1866
1867 }
1868
1869 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
1870 {
1871     // Repaint any overhanging floats (if we know we're the one to paint them).
1872     // Otherwise, bail out.
1873     if (!hasOverhangingFloats())
1874         return;
1875
1876     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
1877     // in this block. Better yet would be to push extra state for the containers of other floats.
1878     LayoutStateDisabler layoutStateDisabler(view());
1879     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1880     FloatingObjectSetIterator end = floatingObjectSet.end();
1881     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1882         FloatingObject* floatingObject = *it;
1883         // Only repaint the object if it is overhanging, is not in its own layer, and
1884         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
1885         // condition is replaced with being a descendant of us.
1886         if (logicalBottomForFloat(floatingObject) > logicalHeight()
1887             && !floatingObject->renderer()->hasSelfPaintingLayer()
1888             && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer()->isDescendantOf(this)))) {
1889
1890             RenderBox* floatingRenderer = floatingObject->renderer();
1891             LayoutRectRecorder recorder(*floatingRenderer);
1892             if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
1893                 floatingRenderer->setShouldDoFullRepaintAfterLayout(true);
1894             else
1895                 floatingRenderer->repaint();
1896
1897             floatingRenderer->repaintOverhangingFloats(false);
1898         }
1899     }
1900 }
1901
1902 void RenderBlockFlow::repaintOverflow()
1903 {
1904     // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1905     // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
1906     LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1907     LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1908     if (hasOverflowClip()) {
1909         // 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.
1910         // 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.
1911         // layoutInlineChildren should be patched to compute the entire repaint rect.
1912         repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1913         repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1914     }
1915
1916     LayoutRect repaintRect;
1917     if (isHorizontalWritingMode())
1918         repaintRect = LayoutRect(repaintLogicalLeft, m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop);
1919     else
1920         repaintRect = LayoutRect(m_repaintLogicalTop, repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1921
1922     // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1923     adjustRectForColumns(repaintRect);
1924
1925     repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1926
1927     if (hasOverflowClip()) {
1928         // Adjust repaint rect for scroll offset
1929         repaintRect.move(-scrolledContentOffset());
1930
1931         // Don't allow this rect to spill out of our overflow box.
1932         repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1933     }
1934
1935     // Make sure the rect is still non-empty after intersecting for overflow above
1936     if (!repaintRect.isEmpty()) {
1937         repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1938         if (hasReflection())
1939             repaintRectangle(reflectedRect(repaintRect));
1940     }
1941
1942     m_repaintLogicalTop = 0;
1943     m_repaintLogicalBottom = 0;
1944 }
1945
1946 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
1947 {
1948     if (!m_floatingObjects)
1949         return;
1950
1951     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1952     FloatingObjectSetIterator end = floatingObjectSet.end();
1953     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1954         FloatingObject* floatingObject = *it;
1955         // Only paint the object if our m_shouldPaint flag is set.
1956         if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
1957             PaintInfo currentPaintInfo(paintInfo);
1958             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
1959             // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
1960             LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y()));
1961             floatingObject->renderer()->paint(currentPaintInfo, childPoint);
1962             if (!preservePhase) {
1963                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
1964                 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
1965                 currentPaintInfo.phase = PaintPhaseFloat;
1966                 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
1967                 currentPaintInfo.phase = PaintPhaseForeground;
1968                 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
1969                 currentPaintInfo.phase = PaintPhaseOutline;
1970                 floatingObject->renderer()->paint(currentPaintInfo, childPoint);
1971             }
1972         }
1973     }
1974 }
1975
1976 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
1977 {
1978     if (m_floatingObjects) {
1979         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1980         FloatingObjectSetIterator end = floatingObjectSet.end();
1981         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1982             FloatingObject* floatingObject = *it;
1983             LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
1984                 offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
1985                 floatingObject->renderer()->width(), floatingObject->renderer()->height());
1986             rootBlock->flipForWritingMode(floatBox);
1987             floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
1988             paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
1989         }
1990     }
1991 }
1992
1993 void RenderBlockFlow::clearFloats(EClear clear)
1994 {
1995     positionNewFloats();
1996     // set y position
1997     LayoutUnit newY = 0;
1998     switch (clear) {
1999     case CLEFT:
2000         newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2001         break;
2002     case CRIGHT:
2003         newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2004         break;
2005     case CBOTH:
2006         newY = lowestFloatLogicalBottom();
2007     default:
2008         break;
2009     }
2010     if (height() < newY)
2011         setLogicalHeight(newY);
2012 }
2013
2014 bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
2015 {
2016     return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
2017 }
2018
2019 void RenderBlockFlow::removeFloatingObjects()
2020 {
2021     if (!m_floatingObjects)
2022         return;
2023
2024     m_floatingObjects->clear();
2025 }
2026
2027 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2028 {
2029     if (!style()->isFlippedBlocksWritingMode())
2030         return point;
2031
2032     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2033     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2034     // case.
2035     if (isHorizontalWritingMode())
2036         return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
2037     return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2038 }
2039
2040 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2041 {
2042     LayoutUnit offset = fixedOffset;
2043     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2044         offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2045     return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2046 }
2047
2048 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2049 {
2050     LayoutUnit offset = fixedOffset;
2051     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2052         offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2053     return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2054 }
2055
2056 LayoutUnit RenderBlockFlow::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2057 {
2058     LayoutUnit left = offsetFromFloats;
2059
2060     if (applyTextIndent && style()->isLeftToRightDirection())
2061         left += textIndentOffset();
2062
2063     return left;
2064 }
2065
2066 LayoutUnit RenderBlockFlow::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
2067 {
2068     LayoutUnit right = offsetFromFloats;
2069
2070     if (applyTextIndent && !style()->isLeftToRightDirection())
2071         right -= textIndentOffset();
2072
2073     return right;
2074 }
2075
2076 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
2077 {
2078     RenderBox* childBox = floatingObject->renderer();
2079     LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2080     LayoutUnit logicalRightOffset; // Constant part of right offset.
2081     // FIXME Bug 102948: This only works for shape outside directly set on this block.
2082     ShapeInsideInfo* shapeInsideInfo = this->layoutShapeInsideInfo();
2083     // FIXME: Implement behavior for right floats.
2084     if (shapeInsideInfo) {
2085         LayoutSize floatLogicalSize = logicalSizeForFloat(floatingObject);
2086         // floatingObject's logicalSize doesn't contain the actual height at this point, so we need to calculate it
2087         floatLogicalSize.setHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2088
2089         // FIXME: If the float doesn't fit in the shape we should push it under the content box
2090         logicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(floatLogicalSize);
2091         if (logicalHeight() > logicalTopOffset)
2092             logicalTopOffset = logicalHeight();
2093
2094         SegmentList segments = shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, floatLogicalSize.height());
2095         // FIXME: Add support for shapes with multiple segments.
2096         if (segments.size() == 1) {
2097             // The segment offsets are relative to the content box.
2098             logicalRightOffset = logicalLeftOffset + segments[0].logicalRight;
2099             logicalLeftOffset += segments[0].logicalLeft;
2100         }
2101     } else {
2102         logicalRightOffset = logicalRightOffsetForContent();
2103     }
2104
2105     LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2106
2107     LayoutUnit floatLogicalLeft;
2108
2109     bool insideFlowThread = flowThreadContainingBlock();
2110
2111     if (childBox->style()->floating() == LeftFloat) {
2112         LayoutUnit heightRemainingLeft = 1;
2113         LayoutUnit heightRemainingRight = 1;
2114         floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2115         while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2116             logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
2117             floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2118             if (insideFlowThread) {
2119                 // Have to re-evaluate all of our offsets, since they may have changed.
2120                 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2121                 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2122                 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2123             }
2124         }
2125         floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2126     } else {
2127         LayoutUnit heightRemainingLeft = 1;
2128         LayoutUnit heightRemainingRight = 1;
2129         floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2130         while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2131             logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
2132             floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2133             if (insideFlowThread) {
2134                 // Have to re-evaluate all of our offsets, since they may have changed.
2135                 logicalRightOffset = logicalRightOffsetForContent(); // Constant part of right offset.
2136                 logicalLeftOffset = logicalLeftOffsetForContent(); // Constant part of left offset.
2137                 floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2138             }
2139         }
2140         // Use the original width of the float here, since the local variable
2141         // |floatLogicalWidth| was capped to the available line width. See
2142         // fast/block/float/clamped-right-float.html.
2143         floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2144     }
2145
2146     return LayoutPoint(floatLogicalLeft, logicalTopOffset);
2147 }
2148
2149 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
2150 {
2151     ASSERT(floatBox->isFloating());
2152
2153     // Create the list of special objects if we don't aleady have one
2154     if (!m_floatingObjects) {
2155         createFloatingObjects();
2156     } else {
2157         // Don't insert the object again if it's already in the list
2158         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2159         FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2160         if (it != floatingObjectSet.end())
2161             return *it;
2162     }
2163
2164     // Create the special object entry & append it to the list
2165
2166     OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
2167
2168     // Our location is irrelevant if we're unsplittable or no pagination is in effect.
2169     // Just go ahead and lay out the float.
2170     bool isChildRenderBlock = floatBox->isRenderBlock();
2171     if (isChildRenderBlock && !floatBox->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
2172         floatBox->setChildNeedsLayout(MarkOnlyThis);
2173
2174     bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2175     if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
2176         floatBox->layoutIfNeeded();
2177     } else {
2178         floatBox->updateLogicalWidth();
2179         floatBox->computeAndSetBlockDirectionMargins(this);
2180     }
2181
2182     setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
2183
2184     return m_floatingObjects->add(newObj.release());
2185 }
2186
2187 void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
2188 {
2189     if (m_floatingObjects) {
2190         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2191         FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
2192         if (it != floatingObjectSet.end()) {
2193             FloatingObject* floatingObject = *it;
2194             if (childrenInline()) {
2195                 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
2196                 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
2197
2198                 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
2199                 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max()) {
2200                     logicalBottom = LayoutUnit::max();
2201                 } else {
2202                     // Special-case zero- and less-than-zero-height floats: those don't touch
2203                     // the line that they're on, but it still needs to be dirtied. This is
2204                     // accomplished by pretending they have a height of 1.
2205                     logicalBottom = max(logicalBottom, logicalTop + 1);
2206                 }
2207                 if (floatingObject->originatingLine()) {
2208                     if (!selfNeedsLayout()) {
2209                         ASSERT(floatingObject->originatingLine()->renderer() == this);
2210                         floatingObject->originatingLine()->markDirty();
2211                     }
2212 #if !ASSERT_DISABLED
2213                     floatingObject->setOriginatingLine(0);
2214 #endif
2215                 }
2216                 markLinesDirtyInBlockRange(0, logicalBottom);
2217             }
2218             m_floatingObjects->remove(floatingObject);
2219         }
2220     }
2221 }
2222
2223 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2224 {
2225     if (!containsFloats())
2226         return;
2227
2228     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2229     FloatingObject* curr = floatingObjectSet.last();
2230     while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
2231         m_floatingObjects->remove(curr);
2232         if (floatingObjectSet.isEmpty())
2233             break;
2234         curr = floatingObjectSet.last();
2235     }
2236 }
2237
2238 bool RenderBlockFlow::positionNewFloats()
2239 {
2240     if (!m_floatingObjects)
2241         return false;
2242
2243     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2244     if (floatingObjectSet.isEmpty())
2245         return false;
2246
2247     // If all floats have already been positioned, then we have no work to do.
2248     if (floatingObjectSet.last()->isPlaced())
2249         return false;
2250
2251     // Move backwards through our floating object list until we find a float that has
2252     // already been positioned. Then we'll be able to move forward, positioning all of
2253     // the new floats that need it.
2254     FloatingObjectSetIterator it = floatingObjectSet.end();
2255     --it; // Go to last item.
2256     FloatingObjectSetIterator begin = floatingObjectSet.begin();
2257     FloatingObject* lastPlacedFloatingObject = 0;
2258     while (it != begin) {
2259         --it;
2260         if ((*it)->isPlaced()) {
2261             lastPlacedFloatingObject = *it;
2262             ++it;
2263             break;
2264         }
2265     }
2266
2267     LayoutUnit logicalTop = logicalHeight();
2268
2269     // The float cannot start above the top position of the last positioned float.
2270     if (lastPlacedFloatingObject)
2271         logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
2272
2273     FloatingObjectSetIterator end = floatingObjectSet.end();
2274     // Now walk through the set of unpositioned floats and place them.
2275     for (; it != end; ++it) {
2276         FloatingObject* floatingObject = *it;
2277         // The containing block is responsible for positioning floats, so if we have floats in our
2278         // list that come from somewhere else, do not attempt to position them.
2279         if (floatingObject->renderer()->containingBlock() != this)
2280             continue;
2281
2282         RenderBox* childBox = floatingObject->renderer();
2283         LayoutRectRecorder childBoxRecorder(*childBox);
2284
2285         LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2286         LayoutRect oldRect = childBox->frameRect();
2287
2288         if (childBox->style()->clear() & CLEFT)
2289             logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2290         if (childBox->style()->clear() & CRIGHT)
2291             logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2292
2293         LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
2294
2295         setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2296
2297         setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2298         setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2299
2300         SubtreeLayoutScope layoutScope(childBox);
2301         LayoutState* layoutState = view()->layoutState();
2302         bool isPaginated = layoutState->isPaginated();
2303         if (isPaginated && !childBox->needsLayout())
2304             childBox->markForPaginationRelayoutIfNeeded(layoutScope);
2305
2306         childBox->layoutIfNeeded();
2307
2308         if (isPaginated) {
2309             // If we are unsplittable and don't fit, then we need to move down.
2310             // We include our margins as part of the unsplittable area.
2311             LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
2312
2313             // See if we have a pagination strut that is making us move down further.
2314             // Note that an unsplittable child can't also have a pagination strut, so this is
2315             // exclusive with the case above.
2316             RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
2317             if (childBlock && childBlock->paginationStrut()) {
2318                 newLogicalTop += childBlock->paginationStrut();
2319                 childBlock->setPaginationStrut(0);
2320             }
2321
2322             if (newLogicalTop != floatLogicalLocation.y()) {
2323                 floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
2324
2325                 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2326                 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2327
2328                 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2329                 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2330
2331                 if (childBlock)
2332                     childBlock->setChildNeedsLayout(MarkOnlyThis);
2333                 childBox->layoutIfNeeded();
2334             }
2335         }
2336
2337         setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
2338
2339         setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2340
2341         m_floatingObjects->addPlacedObject(floatingObject);
2342
2343         if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
2344             shapeOutside->setShapeSize(logicalWidthForChild(childBox), logicalHeightForChild(childBox));
2345
2346         // If the child moved, we have to repaint it.
2347         if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled()
2348             && childBox->checkForRepaintDuringLayout())
2349             childBox->repaintDuringLayoutIfMoved(oldRect);
2350     }
2351     return true;
2352 }
2353
2354 bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
2355 {
2356     if (!m_floatingObjects || hasColumns() || !parent())
2357         return false;
2358
2359     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2360     FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
2361     if (it == floatingObjectSet.end())
2362         return false;
2363
2364     return logicalBottomForFloat(*it) > logicalHeight();
2365 }
2366
2367 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2368 {
2369     ASSERT(!avoidsFloats());
2370
2371     // If the parent or previous sibling doesn't have any floats to add, don't bother.
2372     if (!prev->m_floatingObjects)
2373         return;
2374
2375     logicalLeftOffset += marginLogicalLeft();
2376
2377     const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2378     FloatingObjectSetIterator prevEnd = prevSet.end();
2379     for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2380         FloatingObject* floatingObject = *prevIt;
2381         if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2382             if (!m_floatingObjects || !m_floatingObjects->set().contains(floatingObject)) {
2383                 // We create the floating object list lazily.
2384                 if (!m_floatingObjects)
2385                     createFloatingObjects();
2386
2387                 // Applying the child's margin makes no sense in the case where the child was passed in.
2388                 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2389                 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2390                 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2391                 // will get applied twice.
2392                 LayoutSize offset = isHorizontalWritingMode()
2393                     ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2394                     : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
2395
2396                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
2397             }
2398         }
2399     }
2400 }
2401
2402 LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
2403 {
2404     // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2405     if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
2406         return 0;
2407
2408     LayoutUnit childLogicalTop = child->logicalTop();
2409     LayoutUnit childLogicalLeft = child->logicalLeft();
2410     LayoutUnit lowestFloatLogicalBottom = 0;
2411
2412     // Floats that will remain the child's responsibility to paint should factor into its
2413     // overflow.
2414     FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
2415     for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2416         FloatingObject* floatingObject = *childIt;
2417         LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2418         LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
2419         lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
2420
2421         if (logicalBottom > logicalHeight()) {
2422             // If the object is not in the list, we add it now.
2423             if (!containsFloat(floatingObject->renderer())) {
2424                 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2425                 bool shouldPaint = false;
2426
2427                 // The nearest enclosing layer always paints the float (so that zindex and stacking
2428                 // behaves properly). We always want to propagate the desire to paint the float as
2429                 // far out as we can, to the outermost block that overlaps the float, stopping only
2430                 // if we hit a self-painting layer boundary.
2431                 if (floatingObject->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2432                     floatingObject->setShouldPaint(false);
2433                     shouldPaint = true;
2434                 }
2435                 // We create the floating object list lazily.
2436                 if (!m_floatingObjects)
2437                     createFloatingObjects();
2438
2439                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
2440             }
2441         } else {
2442             if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()
2443                 && floatingObject->renderer()->isDescendantOf(child) && floatingObject->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
2444                 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2445                 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2446                 // layer.
2447                 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2448                 // it should paint.
2449                 floatingObject->setShouldPaint(true);
2450             }
2451
2452             // 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
2453             // child now.
2454             if (floatingObject->isDescendant())
2455                 child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
2456         }
2457     }
2458     return lowestFloatLogicalBottom;
2459 }
2460
2461 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2462 {
2463     if (!m_floatingObjects)
2464         return 0;
2465
2466     return m_floatingObjects->lowestFloatLogicalBottom(floatType);
2467 }
2468
2469 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
2470 {
2471     if (!m_floatingObjects)
2472         return logicalHeight;
2473
2474     LayoutUnit logicalBottom = LayoutUnit::max();
2475     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2476     FloatingObjectSetIterator end = floatingObjectSet.end();
2477     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2478         FloatingObject* floatingObject = *it;
2479         LayoutUnit floatLogicalBottom = logicalBottomForFloat(floatingObject);
2480         ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
2481         if (shapeOutside && (offsetMode == ShapeOutsideFloatShapeOffset)) {
2482             LayoutUnit shapeLogicalBottom = logicalTopForFloat(floatingObject) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
2483             // Use the shapeLogicalBottom unless it extends outside of the margin box, in which case it is clipped.
2484             if (shapeLogicalBottom < floatLogicalBottom)
2485                 floatLogicalBottom = shapeLogicalBottom;
2486         }
2487         if (floatLogicalBottom > logicalHeight)
2488             logicalBottom = min(floatLogicalBottom, logicalBottom);
2489     }
2490
2491     return logicalBottom == LayoutUnit::max() ? LayoutUnit() : logicalBottom;
2492 }
2493
2494 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2495 {
2496     if (!m_floatingObjects)
2497         return false;
2498
2499     LayoutPoint adjustedLocation = accumulatedOffset;
2500     if (isRenderView()) {
2501         adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
2502     }
2503
2504     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2505     FloatingObjectSetIterator begin = floatingObjectSet.begin();
2506     for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
2507         --it;
2508         FloatingObject* floatingObject = *it;
2509         if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
2510             LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
2511             LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
2512             LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
2513             if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
2514                 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2515                 return true;
2516             }
2517         }
2518     }
2519
2520     return false;
2521 }
2522
2523 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2524 {
2525     RenderBlock::adjustForBorderFit(x, left, right);
2526     if (m_floatingObjects && style()->visibility() == VISIBLE) {
2527         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2528         FloatingObjectSetIterator end = floatingObjectSet.end();
2529         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2530             FloatingObject* floatingObject = *it;
2531             // Only examine the object if our m_shouldPaint flag is set.
2532             if (floatingObject->shouldPaint()) {
2533                 LayoutUnit floatLeft = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
2534                 LayoutUnit floatRight = floatLeft + floatingObject->renderer()->width();
2535                 left = min(left, floatLeft);
2536                 right = max(right, floatRight);
2537             }
2538         }
2539     }
2540 }
2541
2542 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2543 {
2544     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2545         return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2546
2547     return fixedOffset;
2548 }
2549
2550 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2551 {
2552     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2553         return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2554
2555     return fixedOffset;
2556 }
2557
2558 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2559     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
2560 {
2561     GapRects result;
2562
2563     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2564
2565     if (!firstLineBox()) {
2566         if (containsStart) {
2567             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
2568             // case.
2569             lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
2570             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
2571             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
2572         }
2573         return result;
2574     }
2575
2576     RootInlineBox* lastSelectedLine = 0;
2577     RootInlineBox* curr;
2578     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2579
2580     // Now paint the gaps for the lines.
2581     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2582         LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
2583         LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
2584
2585         if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
2586             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
2587                 lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
2588         }
2589
2590         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2591         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
2592         LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2593         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
2594             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
2595             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
2596
2597         lastSelectedLine = curr;
2598     }
2599
2600     if (containsStart && !lastSelectedLine) {
2601         // VisibleSelection must start just after our last line.
2602         lastSelectedLine = lastRootBox();
2603     }
2604
2605     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2606         // Go ahead and update our lastY to be the bottom of the last selected line.
2607         lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2608         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2609         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
2610     }
2611     return result;
2612 }
2613
2614 LayoutUnit RenderBlockFlow::logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2615 {
2616     LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
2617     if (logicalLeft == logicalLeftOffsetForContent())
2618         return RenderBlock::logicalLeftSelectionOffset(rootBlock, position);
2619
2620     RenderBlock* cb = this;
2621     while (cb != rootBlock) {
2622         logicalLeft += cb->logicalLeft();
2623         cb = cb->containingBlock();
2624     }
2625     return logicalLeft;
2626 }
2627
2628 LayoutUnit RenderBlockFlow::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
2629 {
2630     LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
2631     if (logicalRight == logicalRightOffsetForContent())
2632         return RenderBlock::logicalRightSelectionOffset(rootBlock, position);
2633
2634     RenderBlock* cb = this;
2635     while (cb != rootBlock) {
2636         logicalRight += cb->logicalLeft();
2637         cb = cb->containingBlock();
2638     }
2639     return logicalRight;
2640 }
2641
2642 /*template <typename CharacterType>
2643 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2644 {
2645     return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2646 }*/
2647
2648 template <typename CharacterType>
2649 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2650 {
2651     ASSERT(style);
2652
2653     TextDirection textDirection = direction;
2654     bool directionalOverride = style->rtlOrdering() == VisualOrder;
2655
2656     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2657     if (textRunNeedsRenderingContext(font))
2658         run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2659
2660     return run;
2661 }
2662
2663 template <typename CharacterType>
2664 static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2665 {
2666     ASSERT(style);
2667
2668     TextDirection textDirection = direction;
2669     bool directionalOverride = style->rtlOrdering() == VisualOrder;
2670     if (flags != DefaultTextRunFlags) {
2671         if (flags & RespectDirection)
2672             textDirection = style->direction();
2673         if (flags & RespectDirectionOverride)
2674             directionalOverride |= isOverride(style->unicodeBidi());
2675     }
2676
2677     TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
2678     if (textRunNeedsRenderingContext(font))
2679         run.setRenderingContext(SVGTextRunRenderingContext::create(context));
2680
2681     return run;
2682 }
2683
2684 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2685 {
2686     return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2687 }
2688
2689 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2690 {
2691     return constructTextRunInternal(context, font, characters, length, style, direction, expansion);
2692 }
2693
2694 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2695 {
2696     if (text->is8Bit())
2697         return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, direction, expansion);
2698     return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, direction, expansion);
2699 }
2700
2701 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion)
2702 {
2703     ASSERT(offset + length <= text->textLength());
2704     if (text->is8Bit())
2705         return constructTextRunInternal(context, font, text->characters8() + offset, length, style, direction, expansion);
2706     return constructTextRunInternal(context, font, text->characters16() + offset, length, style, direction, expansion);
2707 }
2708
2709 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextDirection direction, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2710 {
2711     unsigned length = string.length();
2712     if (!length)
2713         return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, direction, expansion, flags);
2714     if (string.is8Bit())
2715         return constructTextRunInternal(context, font, string.characters8(), length, style, direction, expansion, flags);
2716     return constructTextRunInternal(context, font, string.characters16(), length, style, direction, expansion, flags);
2717 }
2718
2719 TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
2720 {
2721     bool hasStrongDirectionality;
2722     return constructTextRun(context, font, string, style,
2723         determineDirectionality(string, hasStrongDirectionality),
2724         expansion, flags);
2725 }
2726
2727 RootInlineBox* RenderBlockFlow::createRootInlineBox()
2728 {
2729     return new RootInlineBox(this);
2730 }
2731
2732 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
2733 {
2734     if (m_rareData)
2735         return *m_rareData;
2736
2737     m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
2738     return *m_rareData;
2739 }
2740
2741 } // namespace WebCore