Make RenderBlockRareData be in a hashtable instead of being a member variable.
[WebKit-https.git] / Source / WebCore / rendering / RenderBlockFlow.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2007 David Smith (catfish.man@gmail.com)
5  * Copyright (C) 2003-2013 Apple Inc. All rights reserved.
6  * Copyright (C) Research In Motion Limited 2010. All rights reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 #include "config.h"
25 #include "RenderBlockFlow.h"
26
27 #include "Editor.h"
28 #include "FloatingObjects.h"
29 #include "Frame.h"
30 #include "HitTestLocation.h"
31 #include "InlineTextBox.h"
32 #include "LayoutRepainter.h"
33 #include "RenderFlowThread.h"
34 #include "RenderIterator.h"
35 #include "RenderLayer.h"
36 #include "RenderNamedFlowFragment.h"
37 #include "RenderText.h"
38 #include "RenderView.h"
39 #include "SimpleLineLayoutFunctions.h"
40 #include "VerticalPositionCache.h"
41 #include "VisiblePosition.h"
42
43 namespace WebCore {
44
45 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
46
47 struct SameSizeAsMarginInfo {
48     uint32_t bitfields : 16;
49     LayoutUnit margins[2];
50 };
51
52 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
53 COMPILE_ASSERT(sizeof(RenderBlockFlow::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
54
55 // Our MarginInfo state used when laying out block children.
56 RenderBlockFlow::MarginInfo::MarginInfo(RenderBlockFlow& block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
57     : m_atBeforeSideOfBlock(true)
58     , m_atAfterSideOfBlock(false)
59     , m_hasMarginBeforeQuirk(false)
60     , m_hasMarginAfterQuirk(false)
61     , m_determinedMarginBeforeQuirk(false)
62     , m_discardMargin(false)
63 {
64     const RenderStyle& blockStyle = block.style();
65     ASSERT(block.isRenderView() || block.parent());
66     m_canCollapseWithChildren = !block.isRenderView() && !block.isRoot() && !block.isOutOfFlowPositioned()
67         && !block.isFloating() && !block.isTableCell() && !block.hasOverflowClip() && !block.isInlineBlockOrInlineTable()
68         && !block.isRenderFlowThread() && !block.isWritingModeRoot() && !block.parent()->isFlexibleBox()
69         && blockStyle.hasAutoColumnCount() && blockStyle.hasAutoColumnWidth() && !blockStyle.columnSpan();
70
71     m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle.marginBeforeCollapse() != MSEPARATE;
72
73     // If any height other than auto is specified in CSS, then we don't collapse our bottom
74     // margins with our children's margins. To do otherwise would be to risk odd visual
75     // effects when the children overflow out of the parent block and yet still collapse
76     // with it. We also don't collapse if we have any bottom border/padding.
77     m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && !afterBorderPadding
78         && (blockStyle.logicalHeight().isAuto() && !blockStyle.logicalHeight().value()) && blockStyle.marginAfterCollapse() != MSEPARATE;
79     
80     m_quirkContainer = block.isTableCell() || block.isBody();
81
82     m_discardMargin = m_canCollapseMarginBeforeWithChildren && block.mustDiscardMarginBefore();
83
84     m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxPositiveMarginBefore() : LayoutUnit();
85     m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block.mustDiscardMarginBefore()) ? block.maxNegativeMarginBefore() : LayoutUnit();
86 }
87
88 RenderBlockFlow::RenderBlockFlow(Element& element, PassRef<RenderStyle> style)
89     : RenderBlock(element, std::move(style), RenderBlockFlowFlag)
90 {
91     setChildrenInline(true);
92 }
93
94 RenderBlockFlow::RenderBlockFlow(Document& document, PassRef<RenderStyle> style)
95     : RenderBlock(document, std::move(style), RenderBlockFlowFlag)
96 {
97     setChildrenInline(true);
98 }
99
100 RenderBlockFlow::~RenderBlockFlow()
101 {
102 }
103
104 void RenderBlockFlow::insertedIntoTree()
105 {
106     RenderBlock::insertedIntoTree();
107     createRenderNamedFlowFragmentIfNeeded();
108 }
109
110 void RenderBlockFlow::willBeDestroyed()
111 {
112     // Mark as being destroyed to avoid trouble with merges in removeChild().
113     m_beingDestroyed = true;
114
115     if (renderNamedFlowFragment())
116         setRenderNamedFlowFragment(0);
117
118     if (!documentBeingDestroyed()) {
119         if (firstChild() && firstChild()->isRunIn())
120             moveRunInToOriginalPosition(*firstChild());
121     }
122
123     // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
124     // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
125     destroyLeftoverChildren();
126
127     // Destroy our continuation before anything other than anonymous children.
128     // The reason we don't destroy it before anonymous children is that they may
129     // have continuations of their own that are anonymous children of our continuation.
130     RenderBoxModelObject* continuation = this->continuation();
131     if (continuation) {
132         continuation->destroy();
133         setContinuation(0);
134     }
135
136     if (!documentBeingDestroyed()) {
137         if (firstRootBox()) {
138             // We can't wait for RenderBox::destroy to clear the selection,
139             // because by then we will have nuked the line boxes.
140             // FIXME: The FrameSelection should be responsible for this when it
141             // is notified of DOM mutations.
142             if (isSelectionBorder())
143                 view().clearSelection();
144
145             // If we are an anonymous block, then our line boxes might have children
146             // that will outlast this block. In the non-anonymous block case those
147             // children will be destroyed by the time we return from this function.
148             if (isAnonymousBlock()) {
149                 for (auto box = firstRootBox(); box; box = box->nextRootBox()) {
150                     while (auto childBox = box->firstChild())
151                         childBox->removeFromParent();
152                 }
153             }
154         } else if (parent())
155             parent()->dirtyLinesFromChangedChild(this);
156     }
157
158     m_lineBoxes.deleteLineBoxes();
159
160     removeFromDelayedUpdateScrollInfoSet();
161
162     // NOTE: This jumps down to RenderBox, bypassing RenderBlock since it would do duplicate work.
163     RenderBox::willBeDestroyed();
164 }
165
166 void RenderBlockFlow::clearFloats()
167 {
168     if (m_floatingObjects)
169         m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
170
171     HashSet<RenderBox*> oldIntrudingFloatSet;
172     if (!childrenInline() && m_floatingObjects) {
173         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
174         auto end = floatingObjectSet.end();
175         for (auto it = floatingObjectSet.begin(); it != end; ++it) {
176             FloatingObject* floatingObject = it->get();
177             if (!floatingObject->isDescendant())
178                 oldIntrudingFloatSet.add(&floatingObject->renderer());
179         }
180     }
181
182     // Inline blocks are covered by the isReplaced() check in the avoidFloats method.
183     if (avoidsFloats() || isRoot() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
184         if (m_floatingObjects)
185             m_floatingObjects->clear();
186         if (!oldIntrudingFloatSet.isEmpty())
187             markAllDescendantsWithFloatsForLayout();
188         return;
189     }
190
191     RendererToFloatInfoMap floatMap;
192
193     if (m_floatingObjects) {
194         if (childrenInline())
195             m_floatingObjects->moveAllToFloatInfoMap(floatMap);
196         else
197             m_floatingObjects->clear();
198     }
199
200     // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add 
201     // floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
202     // See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
203     if (!parent() || !parent()->isRenderBlockFlow())
204         return;
205
206     // Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
207     // out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
208     // to avoid floats.
209     RenderBlockFlow* parentBlock = toRenderBlockFlow(parent());
210     bool parentHasFloats = false;
211     RenderObject* prev = previousSibling();
212     while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlockFlow() || toRenderBlockFlow(prev)->avoidsFloats())) {
213         if (prev->isFloating())
214             parentHasFloats = true;
215         prev = prev->previousSibling();
216     }
217
218     // First add in floats from the parent.
219     LayoutUnit logicalTopOffset = logicalTop();
220     if (parentHasFloats)
221         addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
222     
223     LayoutUnit logicalLeftOffset = 0;
224     if (prev)
225         logicalTopOffset -= toRenderBox(prev)->logicalTop();
226     else {
227         prev = parentBlock;
228         logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
229     }
230
231     // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.    
232     RenderBlockFlow* block = toRenderBlockFlow(prev);
233     if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
234         addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
235
236     if (childrenInline()) {
237         LayoutUnit changeLogicalTop = LayoutUnit::max();
238         LayoutUnit changeLogicalBottom = LayoutUnit::min();
239         if (m_floatingObjects) {
240             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
241             auto end = floatingObjectSet.end();
242             for (auto it = floatingObjectSet.begin(); it != end; ++it) {
243                 FloatingObject* floatingObject = it->get();
244                 std::unique_ptr<FloatingObject> oldFloatingObject = floatMap.take(&floatingObject->renderer());
245                 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
246                 if (oldFloatingObject) {
247                     LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject.get());
248                     if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject.get()) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject.get())) {
249                         changeLogicalTop = 0;
250                         changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
251                     } else {
252                         if (logicalBottom != oldLogicalBottom) {
253                             changeLogicalTop = std::min(changeLogicalTop, std::min(logicalBottom, oldLogicalBottom));
254                             changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalBottom, oldLogicalBottom));
255                         }
256                         LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
257                         LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject.get());
258                         if (logicalTop != oldLogicalTop) {
259                             changeLogicalTop = std::min(changeLogicalTop, std::min(logicalTop, oldLogicalTop));
260                             changeLogicalBottom = std::max(changeLogicalBottom, std::max(logicalTop, oldLogicalTop));
261                         }
262                     }
263
264                     if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
265                         ASSERT(&oldFloatingObject->originatingLine()->renderer() == this);
266                         oldFloatingObject->originatingLine()->markDirty();
267                     }
268                 } else {
269                     changeLogicalTop = 0;
270                     changeLogicalBottom = std::max(changeLogicalBottom, logicalBottom);
271                 }
272             }
273         }
274
275         auto end = floatMap.end();
276         for (auto it = floatMap.begin(); it != end; ++it) {
277             FloatingObject* floatingObject = it->value.get();
278             if (!floatingObject->isDescendant()) {
279                 changeLogicalTop = 0;
280                 changeLogicalBottom = std::max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
281             }
282         }
283
284         markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
285     } else if (!oldIntrudingFloatSet.isEmpty()) {
286         // If there are previously intruding floats that no longer intrude, then children with floats
287         // should also get layout because they might need their floating object lists cleared.
288         if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size())
289             markAllDescendantsWithFloatsForLayout();
290         else {
291             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
292             auto end = floatingObjectSet.end();
293             for (auto it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
294                 oldIntrudingFloatSet.remove(&(*it)->renderer());
295             if (!oldIntrudingFloatSet.isEmpty())
296                 markAllDescendantsWithFloatsForLayout();
297         }
298     }
299 }
300
301 void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
302 {
303     ASSERT(needsLayout());
304
305     if (!relayoutChildren && simplifiedLayout())
306         return;
307
308     LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
309
310     if (updateLogicalWidthAndColumnWidth())
311         relayoutChildren = true;
312
313     clearFloats();
314
315     LayoutUnit previousHeight = logicalHeight();
316     // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
317     // for consistency with other render classes?
318     setLogicalHeight(0);
319
320     bool pageLogicalHeightChanged = false;
321     bool hasSpecifiedPageLogicalHeight = false;
322     checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
323
324     const RenderStyle& styleToUse = style();
325     LayoutStateMaintainer statePusher(&view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse.isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
326
327     prepareShapesAndPaginationBeforeBlockLayout(relayoutChildren);
328     if (!relayoutChildren)
329         relayoutChildren = namedFlowFragmentNeedsUpdate();
330
331     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
332     // our current maximal positive and negative margins. These values are used when we
333     // are collapsed with adjacent blocks, so for example, if you have block A and B
334     // collapsing together, then you'd take the maximal positive margin from both A and B
335     // and subtract it from the maximal negative margin from both A and B to get the
336     // true collapsed margin. This algorithm is recursive, so when we finish layout()
337     // our block knows its current maximal positive/negative values.
338     //
339     // Start out by setting our margin values to our current margins. Table cells have
340     // no margins, so we don't fill in the values for table cells.
341     bool isCell = isTableCell();
342     if (!isCell) {
343         initMaxMarginValues();
344         
345         setHasMarginBeforeQuirk(styleToUse.hasMarginBeforeQuirk());
346         setHasMarginAfterQuirk(styleToUse.hasMarginAfterQuirk());
347         setPaginationStrut(0);
348     }
349
350     LayoutUnit repaintLogicalTop = 0;
351     LayoutUnit repaintLogicalBottom = 0;
352     LayoutUnit maxFloatLogicalBottom = 0;
353     if (!firstChild() && !isAnonymousBlock())
354         setChildrenInline(true);
355     if (childrenInline())
356         layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
357     else
358         layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
359
360     // Expand our intrinsic height to encompass floats.
361     LayoutUnit toAdd = borderAndPaddingAfter() + scrollbarLogicalHeight();
362     if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
363         setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
364     
365     if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher) || relayoutToAvoidWidows(statePusher)) {
366         ASSERT(!shouldBreakAtLineToAvoidWidow());
367         return;
368     }
369
370     // Calculate our new height.
371     LayoutUnit oldHeight = logicalHeight();
372     LayoutUnit oldClientAfterEdge = clientLogicalBottom();
373
374     // Before updating the final size of the flow thread make sure a forced break is applied after the content.
375     // This ensures the size information is correctly computed for the last auto-height region receiving content.
376     if (isRenderFlowThread())
377         toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
378
379     updateLogicalHeight();
380     LayoutUnit newHeight = logicalHeight();
381     if (oldHeight != newHeight) {
382         if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
383             // One of our children's floats may have become an overhanging float for us. We need to look for it.
384             for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
385                 if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
386                     RenderBlockFlow& block = toRenderBlockFlow(*child);
387                     if (block.lowestFloatLogicalBottom() + block.logicalTop() > newHeight)
388                         addOverhangingFloats(block, false);
389                 }
390             }
391         }
392     }
393
394     bool heightChanged = (previousHeight != newHeight);
395     if (heightChanged)
396         relayoutChildren = true;
397
398     layoutPositionedObjects(relayoutChildren || isRoot());
399
400     updateShapesAfterBlockLayout(heightChanged);
401
402     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
403     computeOverflow(oldClientAfterEdge);
404     
405     statePusher.pop();
406
407     fitBorderToLinesIfNeeded();
408
409     if (view().layoutState()->m_pageLogicalHeight)
410         setPageLogicalOffset(view().layoutState()->pageLogicalOffset(this, logicalTop()));
411
412     updateLayerTransform();
413
414     // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
415     // we overflow or not.
416     updateScrollInfoAfterLayout();
417
418     // FIXME: This repaint logic should be moved into a separate helper function!
419     // Repaint with our new bounds if they are different from our old bounds.
420     bool didFullRepaint = repainter.repaintAfterLayout();
421     if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse.visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
422         // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
423         // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
424         LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
425         LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
426         if (hasOverflowClip()) {
427             // 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.
428             // 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.
429             // layoutInlineChildren should be patched to compute the entire repaint rect.
430             repaintLogicalLeft = std::min(repaintLogicalLeft, logicalLeftLayoutOverflow());
431             repaintLogicalRight = std::max(repaintLogicalRight, logicalRightLayoutOverflow());
432         }
433         
434         LayoutRect repaintRect;
435         if (isHorizontalWritingMode())
436             repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
437         else
438             repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
439
440         // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
441         adjustRectForColumns(repaintRect);
442
443         repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
444         
445         if (hasOverflowClip()) {
446             // Adjust repaint rect for scroll offset
447             repaintRect.move(-scrolledContentOffset());
448
449             // Don't allow this rect to spill out of our overflow box.
450             repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
451         }
452
453         // Make sure the rect is still non-empty after intersecting for overflow above
454         if (!repaintRect.isEmpty()) {
455             repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
456             if (hasReflection())
457                 repaintRectangle(reflectedRect(repaintRect));
458         }
459     }
460
461     clearNeedsLayout();
462 }
463
464 void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
465 {
466     dirtyForLayoutFromPercentageHeightDescendants();
467
468     LayoutUnit beforeEdge = borderAndPaddingBefore();
469     LayoutUnit afterEdge = borderAndPaddingAfter() + scrollbarLogicalHeight();
470
471     setLogicalHeight(beforeEdge);
472     
473     // Lay out our hypothetical grid line as though it occurs at the top of the block.
474     if (view().layoutState()->lineGrid() == this)
475         layoutLineGridBox();
476
477     // The margin struct caches all our current margin collapsing state.
478     MarginInfo marginInfo(*this, beforeEdge, afterEdge);
479
480     // Fieldsets need to find their legend and position it inside the border of the object.
481     // The legend then gets skipped during normal layout. The same is true for ruby text.
482     // It doesn't get included in the normal layout process but is instead skipped.
483     RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
484
485     LayoutUnit previousFloatLogicalBottom = 0;
486     maxFloatLogicalBottom = 0;
487
488     RenderBox* next = firstChildBox();
489
490     while (next) {
491         RenderBox& child = *next;
492         next = child.nextSiblingBox();
493
494         if (childToExclude == &child)
495             continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
496
497         updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
498
499         if (child.isOutOfFlowPositioned()) {
500             child.containingBlock()->insertPositionedObject(child);
501             adjustPositionedBlock(child, marginInfo);
502             continue;
503         }
504         if (child.isFloating()) {
505             insertFloatingObject(child);
506             adjustFloatingBlock(marginInfo);
507             continue;
508         }
509
510         // Lay out the child.
511         layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
512     }
513     
514     // Now do the handling of the bottom of the block, adding in our bottom border/padding and
515     // determining the correct collapsed bottom margin information.
516     handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
517 }
518
519 void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
520 {
521     if (m_lineLayoutPath == UndeterminedPath)
522         m_lineLayoutPath = SimpleLineLayout::canUseFor(*this) ? SimpleLinesPath : LineBoxesPath;
523
524     if (m_lineLayoutPath == SimpleLinesPath) {
525         deleteLineBoxesBeforeSimpleLineLayout();
526         layoutSimpleLines(repaintLogicalTop, repaintLogicalBottom);
527         return;
528     }
529
530     m_simpleLineLayout = nullptr;
531     layoutLineBoxes(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
532 }
533
534 void RenderBlockFlow::layoutBlockChild(RenderBox& child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
535 {
536     LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
537     LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
538
539     // The child is a normal flow object. Compute the margins we will use for collapsing now.
540     child.computeAndSetBlockDirectionMargins(this);
541
542     // Try to guess our correct logical top position. In most cases this guess will
543     // be correct. Only if we're wrong (when we compute the real logical top position)
544     // will we have to potentially relayout.
545     LayoutUnit estimateWithoutPagination;
546     LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
547
548     // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
549     LayoutRect oldRect = child.frameRect();
550     LayoutUnit oldLogicalTop = logicalTopForChild(child);
551
552 #if !ASSERT_DISABLED
553     LayoutSize oldLayoutDelta = view().layoutDelta();
554 #endif
555     // Go ahead and position the child as though it didn't collapse with the top.
556     setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
557     estimateRegionRangeForBoxChild(child);
558
559     RenderBlockFlow* childBlockFlow = child.isRenderBlockFlow() ? toRenderBlockFlow(&child) : nullptr;
560     bool markDescendantsWithFloats = false;
561     if (logicalTopEstimate != oldLogicalTop && !child.avoidsFloats() && childBlockFlow && childBlockFlow->containsFloats())
562         markDescendantsWithFloats = true;
563 #if ENABLE(SUBPIXEL_LAYOUT)
564     else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
565         // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
566         // very large elements. If it does the comparison with oldLogicalTop might yield a
567         // false negative as adding and removing margins, borders etc from a saturated number
568         // might yield incorrect results. If this is the case always mark for layout.
569         markDescendantsWithFloats = true;
570 #endif
571     else if (!child.avoidsFloats() || child.shrinkToAvoidFloats()) {
572         // If an element might be affected by the presence of floats, then always mark it for
573         // layout.
574         LayoutUnit fb = std::max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
575         if (fb > logicalTopEstimate)
576             markDescendantsWithFloats = true;
577     }
578
579     if (childBlockFlow) {
580         if (markDescendantsWithFloats)
581             childBlockFlow->markAllDescendantsWithFloatsForLayout();
582         if (!child.isWritingModeRoot())
583             previousFloatLogicalBottom = std::max(previousFloatLogicalBottom, oldLogicalTop + childBlockFlow->lowestFloatLogicalBottom());
584     }
585
586     if (!child.needsLayout())
587         child.markForPaginationRelayoutIfNeeded();
588
589     bool childHadLayout = child.everHadLayout();
590     bool childNeededLayout = child.needsLayout();
591     if (childNeededLayout)
592         child.layout();
593
594     // Cache if we are at the top of the block right now.
595     bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
596
597     // Now determine the correct ypos based off examination of collapsing margin
598     // values.
599     LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
600
601     // Now check for clear.
602     LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
603     
604     bool paginated = view().layoutState()->isPaginated();
605     if (paginated)
606         logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child, atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
607
608     setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
609
610     // Now we have a final top position. See if it really does end up being different from our estimate.
611     // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
612     // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
613     if (logicalTopAfterClear != logicalTopEstimate || child.needsLayout() || (paginated && childBlockFlow && childBlockFlow->shouldBreakAtLineToAvoidWidow())) {
614         if (child.shrinkToAvoidFloats()) {
615             // The child's width depends on the line width.
616             // When the child shifts to clear an item, its width can
617             // change (because it has more available line width).
618             // So go ahead and mark the item as dirty.
619             child.setChildNeedsLayout(MarkOnlyThis);
620         }
621         
622         if (childBlockFlow) {
623             if (!child.avoidsFloats() && childBlockFlow->containsFloats())
624                 childBlockFlow->markAllDescendantsWithFloatsForLayout();
625             if (!child.needsLayout())
626                 child.markForPaginationRelayoutIfNeeded();
627         }
628
629         // Our guess was wrong. Make the child lay itself out again.
630         child.layoutIfNeeded();
631     }
632
633     if (updateRegionRangeForBoxChild(child)) {
634         child.setNeedsLayout(MarkOnlyThis);
635         child.layoutIfNeeded();
636     }
637
638     // We are no longer at the top of the block if we encounter a non-empty child.  
639     // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
640     if (marginInfo.atBeforeSideOfBlock() && !child.isSelfCollapsingBlock())
641         marginInfo.setAtBeforeSideOfBlock(false);
642
643     // Now place the child in the correct left position
644     determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
645
646     LayoutSize childOffset = child.location() - oldRect.location();
647 #if ENABLE(CSS_SHAPES)
648     relayoutShapeDescendantIfMoved(child.isRenderBlock() ? toRenderBlock(&child) : nullptr, childOffset);
649 #endif
650
651     // Update our height now that the child has been placed in the correct position.
652     setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
653     if (mustSeparateMarginAfterForChild(child)) {
654         setLogicalHeight(logicalHeight() + marginAfterForChild(child));
655         marginInfo.clearMargin();
656     }
657     // If the child has overhanging floats that intrude into following siblings (or possibly out
658     // of this block), then the parent gets notified of the floats now.
659     if (childBlockFlow && childBlockFlow->containsFloats())
660         maxFloatLogicalBottom = std::max(maxFloatLogicalBottom, addOverhangingFloats(*childBlockFlow, !childNeededLayout));
661
662     if (childOffset.width() || childOffset.height()) {
663         view().addLayoutDelta(childOffset);
664
665         // If the child moved, we have to repaint it as well as any floating/positioned
666         // descendants. An exception is if we need a layout. In this case, we know we're going to
667         // repaint ourselves (and the child) anyway.
668         if (childHadLayout && !selfNeedsLayout() && child.checkForRepaintDuringLayout())
669             child.repaintDuringLayoutIfMoved(oldRect);
670     }
671
672     if (!childHadLayout && child.checkForRepaintDuringLayout()) {
673         child.repaint();
674         child.repaintOverhangingFloats(true);
675     }
676
677     if (paginated) {
678         // Check for an after page/column break.
679         LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
680         if (newHeight != height())
681             setLogicalHeight(newHeight);
682     }
683
684     ASSERT(view().layoutDeltaMatches(oldLayoutDelta));
685 }
686
687 void RenderBlockFlow::adjustPositionedBlock(RenderBox& child, const MarginInfo& marginInfo)
688 {
689     bool isHorizontal = isHorizontalWritingMode();
690     bool hasStaticBlockPosition = child.style().hasStaticBlockPosition(isHorizontal);
691     
692     LayoutUnit logicalTop = logicalHeight();
693     updateStaticInlinePositionForChild(child, logicalTop);
694
695     if (!marginInfo.canCollapseWithMarginBefore()) {
696         // Positioned blocks don't collapse margins, so add the margin provided by
697         // the container now. The child's own margin is added later when calculating its logical top.
698         LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
699         LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
700         logicalTop += collapsedBeforePos - collapsedBeforeNeg;
701     }
702     
703     RenderLayer* childLayer = child.layer();
704     if (childLayer->staticBlockPosition() != logicalTop) {
705         childLayer->setStaticBlockPosition(logicalTop);
706         if (hasStaticBlockPosition)
707             child.setChildNeedsLayout(MarkOnlyThis);
708     }
709 }
710
711 void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
712 {
713     // The float should be positioned taking into account the bottom margin
714     // of the previous flow. We add that margin into the height, get the
715     // float positioned properly, and then subtract the margin out of the
716     // height again. In the case of self-collapsing blocks, we always just
717     // use the top margins, since the self-collapsing block collapsed its
718     // own bottom margin into its top margin.
719     //
720     // Note also that the previous flow may collapse its margin into the top of
721     // our block. If this is the case, then we do not add the margin in to our
722     // height when computing the position of the float. This condition can be tested
723     // for by simply calling canCollapseWithMarginBefore. See
724     // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
725     // an example of this scenario.
726     LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
727     setLogicalHeight(logicalHeight() + marginOffset);
728     positionNewFloats();
729     setLogicalHeight(logicalHeight() - marginOffset);
730 }
731
732 void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox& child, LayoutUnit logicalTop)
733 {
734     if (child.style().isOriginalDisplayInlineType())
735         setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
736     else
737         setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
738 }
739
740 void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox& child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
741 {
742     if (flowThreadContainingBlock()) {
743         // Shift the inline position to exclude the region offset.
744         inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
745     }
746     child.layer()->setStaticInlinePosition(inlinePosition);
747 }
748
749 RenderBlockFlow::MarginValues RenderBlockFlow::marginValuesForChild(RenderBox& child) const
750 {
751     LayoutUnit childBeforePositive = 0;
752     LayoutUnit childBeforeNegative = 0;
753     LayoutUnit childAfterPositive = 0;
754     LayoutUnit childAfterNegative = 0;
755
756     LayoutUnit beforeMargin = 0;
757     LayoutUnit afterMargin = 0;
758
759     RenderBlockFlow* childRenderBlock = child.isRenderBlockFlow() ? toRenderBlockFlow(&child) : nullptr;
760     
761     // If the child has the same directionality as we do, then we can just return its
762     // margins in the same direction.
763     if (!child.isWritingModeRoot()) {
764         if (childRenderBlock) {
765             childBeforePositive = childRenderBlock->maxPositiveMarginBefore();
766             childBeforeNegative = childRenderBlock->maxNegativeMarginBefore();
767             childAfterPositive = childRenderBlock->maxPositiveMarginAfter();
768             childAfterNegative = childRenderBlock->maxNegativeMarginAfter();
769         } else {
770             beforeMargin = child.marginBefore();
771             afterMargin = child.marginAfter();
772         }
773     } else if (child.isHorizontalWritingMode() == isHorizontalWritingMode()) {
774         // The child has a different directionality. If the child is parallel, then it's just
775         // flipped relative to us. We can use the margins for the opposite edges.
776         if (childRenderBlock) {
777             childBeforePositive = childRenderBlock->maxPositiveMarginAfter();
778             childBeforeNegative = childRenderBlock->maxNegativeMarginAfter();
779             childAfterPositive = childRenderBlock->maxPositiveMarginBefore();
780             childAfterNegative = childRenderBlock->maxNegativeMarginBefore();
781         } else {
782             beforeMargin = child.marginAfter();
783             afterMargin = child.marginBefore();
784         }
785     } else {
786         // The child is perpendicular to us, which means its margins don't collapse but are on the
787         // "logical left/right" sides of the child box. We can just return the raw margin in this case.
788         beforeMargin = marginBeforeForChild(child);
789         afterMargin = marginAfterForChild(child);
790     }
791
792     // Resolve uncollapsing margins into their positive/negative buckets.
793     if (beforeMargin) {
794         if (beforeMargin > 0)
795             childBeforePositive = beforeMargin;
796         else
797             childBeforeNegative = -beforeMargin;
798     }
799     if (afterMargin) {
800         if (afterMargin > 0)
801             childAfterPositive = afterMargin;
802         else
803             childAfterNegative = -afterMargin;
804     }
805
806     return MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
807 }
808
809 LayoutUnit RenderBlockFlow::collapseMargins(RenderBox& child, MarginInfo& marginInfo)
810 {
811     bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
812     bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
813     bool childIsSelfCollapsing = child.isSelfCollapsingBlock();
814
815     // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
816     childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
817
818     // Get the four margin values for the child and cache them.
819     const MarginValues childMargins = marginValuesForChild(child);
820
821     // Get our max pos and neg top margins.
822     LayoutUnit posTop = childMargins.positiveMarginBefore();
823     LayoutUnit negTop = childMargins.negativeMarginBefore();
824
825     // For self-collapsing blocks, collapse our bottom margins into our
826     // top to get new posTop and negTop values.
827     if (childIsSelfCollapsing) {
828         posTop = std::max(posTop, childMargins.positiveMarginAfter());
829         negTop = std::max(negTop, childMargins.negativeMarginAfter());
830     }
831     
832     // See if the top margin is quirky. We only care if this child has
833     // margins that will collapse with us.
834     bool topQuirk = hasMarginBeforeQuirk(child);
835
836     if (marginInfo.canCollapseWithMarginBefore()) {
837         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
838             // This child is collapsing with the top of the
839             // block. If it has larger margin values, then we need to update
840             // our own maximal values.
841             if (!document().inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
842                 setMaxMarginBeforeValues(std::max(posTop, maxPositiveMarginBefore()), std::max(negTop, maxNegativeMarginBefore()));
843
844             // The minute any of the margins involved isn't a quirk, don't
845             // collapse it away, even if the margin is smaller (www.webreference.com
846             // has an example of this, a <dt> with 0.8em author-specified inside
847             // a <dl> inside a <td>.
848             if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
849                 setHasMarginBeforeQuirk(false);
850                 marginInfo.setDeterminedMarginBeforeQuirk(true);
851             }
852
853             if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
854                 // We have no top margin and our top child has a quirky margin.
855                 // We will pick up this quirky margin and pass it through.
856                 // This deals with the <td><div><p> case.
857                 // Don't do this for a block that split two inlines though. You do
858                 // still apply margins in this case.
859                 setHasMarginBeforeQuirk(true);
860         } else
861             // The before margin of the container will also discard all the margins it is collapsing with.
862             setMustDiscardMarginBefore();
863     }
864
865     // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard. 
866     if (childDiscardMarginBefore) {
867         marginInfo.setDiscardMargin(true);
868         marginInfo.clearMargin();
869     }
870
871     if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
872         marginInfo.setHasMarginBeforeQuirk(topQuirk);
873
874     LayoutUnit beforeCollapseLogicalTop = logicalHeight();
875     LayoutUnit logicalTop = beforeCollapseLogicalTop;
876     if (childIsSelfCollapsing) {
877         // 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.
878         // Also, the child's top position equals the logical height of the container.
879         if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
880             // This child has no height. We need to compute our
881             // position before we collapse the child's margins together,
882             // so that we can get an accurate position for the zero-height block.
883             LayoutUnit collapsedBeforePos = std::max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
884             LayoutUnit collapsedBeforeNeg = std::max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
885             marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
886             
887             // Now collapse the child's margins together, which means examining our
888             // bottom margin values as well. 
889             marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
890             marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
891
892             if (!marginInfo.canCollapseWithMarginBefore())
893                 // We need to make sure that the position of the self-collapsing block
894                 // is correct, since it could have overflowing content
895                 // that needs to be positioned correctly (e.g., a block that
896                 // had a specified height of 0 but that actually had subcontent).
897                 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
898         }
899     } else {
900         if (mustSeparateMarginBeforeForChild(child)) {
901             ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
902             // If we are at the before side of the block and we collapse, ignore the computed margin
903             // and just add the child margin to the container height. This will correctly position
904             // the child inside the container.
905             LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
906             setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
907             logicalTop = logicalHeight();
908         } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
909             || (!marginInfo.canCollapseMarginBeforeWithChildren()
910             && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
911             // We're collapsing with a previous sibling's margins and not
912             // with the top of the block.
913             setLogicalHeight(logicalHeight() + std::max(marginInfo.positiveMargin(), posTop) - std::max(marginInfo.negativeMargin(), negTop));
914             logicalTop = logicalHeight();
915         }
916
917         marginInfo.setDiscardMargin(childDiscardMarginAfter);
918         
919         if (!marginInfo.discardMargin()) {
920             marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
921             marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
922         } else
923             marginInfo.clearMargin();
924
925         if (marginInfo.margin())
926             marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
927     }
928     
929     // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
930     // collapsed into the page edge.
931     LayoutState* layoutState = view().layoutState();
932     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
933         && hasNextPage(beforeCollapseLogicalTop)) {
934         LayoutUnit oldLogicalTop = logicalTop;
935         logicalTop = std::min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
936         setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
937     }
938
939     // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
940     // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
941     // or clear it anyway, so don't worry about any floating children it may contain.
942     LayoutUnit oldLogicalHeight = logicalHeight();
943     setLogicalHeight(logicalTop);
944     RenderObject* prev = child.previousSibling();
945     if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
946         RenderBlockFlow& block = toRenderBlockFlow(*prev);
947         if (block.containsFloats() && !block.avoidsFloats() && (block.logicalTop() + block.lowestFloatLogicalBottom()) > logicalTop)
948             addOverhangingFloats(block, false);
949     }
950     setLogicalHeight(oldLogicalHeight);
951
952     return logicalTop;
953 }
954
955 LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox& child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
956 {
957     LayoutUnit heightIncrease = getClearDelta(child, yPos);
958     if (!heightIncrease)
959         return yPos;
960
961     if (child.isSelfCollapsingBlock()) {
962         bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
963
964         // For self-collapsing blocks that clear, they can still collapse their
965         // margins with following siblings. Reset the current margins to represent
966         // the self-collapsing block's margins only.
967         // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
968         if (!childDiscardMargin) {
969             MarginValues childMargins = marginValuesForChild(child);
970             marginInfo.setPositiveMargin(std::max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
971             marginInfo.setNegativeMargin(std::max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
972         } else
973             marginInfo.clearMargin();
974         marginInfo.setDiscardMargin(childDiscardMargin);
975
976         // CSS2.1 states:
977         // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with 
978         // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
979         // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
980         // for a block with height - if none is found then don't allow the margins to collapse with the parent.
981         bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
982         for (RenderBox* curr = child.nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
983             if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
984                 wouldCollapseMarginsWithParent = false;
985         }
986         if (wouldCollapseMarginsWithParent)
987             marginInfo.setCanCollapseMarginAfterWithChildren(false);
988
989         // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
990         // Move the top of the child box to the bottom of the float ignoring the child's top margin.
991         LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
992         setLogicalHeight(child.logicalTop() - collapsedMargin);
993         // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
994         heightIncrease -= std::max(LayoutUnit(), collapsedMargin);
995     } else
996         // Increase our height by the amount we had to clear.
997         setLogicalHeight(logicalHeight() + heightIncrease);
998     
999     if (marginInfo.canCollapseWithMarginBefore()) {
1000         // We can no longer collapse with the top of the block since a clear
1001         // occurred. The empty blocks collapse into the cleared block.
1002         // FIXME: This isn't quite correct. Need clarification for what to do
1003         // if the height the cleared block is offset by is smaller than the
1004         // margins involved.
1005         setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
1006         marginInfo.setAtBeforeSideOfBlock(false);
1007
1008         // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
1009         setMustDiscardMarginBefore(style().marginBeforeCollapse() == MDISCARD);
1010     }
1011
1012     LayoutUnit logicalTop = yPos + heightIncrease;
1013     // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
1014     // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
1015     if (containsFloats() && child.isRenderBlockFlow() && !toRenderBlockFlow(child).containsFloats() && !child.avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
1016         toRenderBlockFlow(child).addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
1017
1018     return logicalTop;
1019 }
1020
1021 void RenderBlockFlow::marginBeforeEstimateForChild(RenderBox& child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
1022 {
1023     // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
1024     // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
1025     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1026     if ((document().inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child.style().marginBeforeCollapse() == MSEPARATE)
1027         return;
1028
1029     // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
1030     // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
1031     if (child.style().marginBeforeCollapse() == MDISCARD) {
1032         positiveMarginBefore = 0;
1033         negativeMarginBefore = 0;
1034         discardMarginBefore = true;
1035         return;
1036     }
1037
1038     LayoutUnit beforeChildMargin = marginBeforeForChild(child);
1039     positiveMarginBefore = std::max(positiveMarginBefore, beforeChildMargin);
1040     negativeMarginBefore = std::max(negativeMarginBefore, -beforeChildMargin);
1041
1042     if (!child.isRenderBlockFlow())
1043         return;
1044     
1045     RenderBlockFlow& childBlock = toRenderBlockFlow(child);
1046     if (childBlock.childrenInline() || childBlock.isWritingModeRoot())
1047         return;
1048
1049     MarginInfo childMarginInfo(childBlock, childBlock.borderAndPaddingBefore(), childBlock.borderAndPaddingAfter());
1050     if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
1051         return;
1052
1053     RenderBox* grandchildBox = childBlock.firstChildBox();
1054     for (; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
1055         if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
1056             break;
1057     }
1058     
1059     // Give up if there is clearance on the box, since it probably won't collapse into us.
1060     if (!grandchildBox || grandchildBox->style().clear() != CNONE)
1061         return;
1062
1063     // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
1064     if (grandchildBox->needsLayout()) {
1065         grandchildBox->computeAndSetBlockDirectionMargins(this);
1066         if (grandchildBox->isRenderBlock()) {
1067             RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
1068             grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style().hasMarginBeforeQuirk());
1069             grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style().hasMarginAfterQuirk());
1070         }
1071     }
1072
1073     // Collapse the margin of the grandchild box with our own to produce an estimate.
1074     childBlock.marginBeforeEstimateForChild(*grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1075 }
1076
1077 LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox& child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
1078 {
1079     // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
1080     // relayout if there are intruding floats.
1081     LayoutUnit logicalTopEstimate = logicalHeight();
1082     if (!marginInfo.canCollapseWithMarginBefore()) {
1083         LayoutUnit positiveMarginBefore = 0;
1084         LayoutUnit negativeMarginBefore = 0;
1085         bool discardMarginBefore = false;
1086         if (child.selfNeedsLayout()) {
1087             // Try to do a basic estimation of how the collapse is going to go.
1088             marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
1089         } else {
1090             // Use the cached collapsed margin values from a previous layout. Most of the time they
1091             // will be right.
1092             MarginValues marginValues = marginValuesForChild(child);
1093             positiveMarginBefore = std::max(positiveMarginBefore, marginValues.positiveMarginBefore());
1094             negativeMarginBefore = std::max(negativeMarginBefore, marginValues.negativeMarginBefore());
1095             discardMarginBefore = mustDiscardMarginBeforeForChild(child);
1096         }
1097
1098         // Collapse the result with our current margins.
1099         if (!discardMarginBefore)
1100             logicalTopEstimate += std::max(marginInfo.positiveMargin(), positiveMarginBefore) - std::max(marginInfo.negativeMargin(), negativeMarginBefore);
1101     }
1102
1103     // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
1104     // page.
1105     LayoutState* layoutState = view().layoutState();
1106     if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
1107         && hasNextPage(logicalHeight()))
1108         logicalTopEstimate = std::min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
1109
1110     logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
1111     
1112     estimateWithoutPagination = logicalTopEstimate;
1113
1114     if (layoutState->isPaginated()) {
1115         // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1116         logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
1117     
1118         // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1119         logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
1120         
1121         if (!child.selfNeedsLayout() && child.isRenderBlock())
1122             logicalTopEstimate += toRenderBlock(child).paginationStrut();
1123     }
1124
1125     return logicalTopEstimate;
1126 }
1127
1128 void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
1129 {
1130     if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
1131         // 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.
1132         // Don't update the max margin values because we won't need them anyway.
1133         if (marginInfo.discardMargin()) {
1134             setMustDiscardMarginAfter();
1135             return;
1136         }
1137
1138         // Update our max pos/neg bottom margins, since we collapsed our bottom margins
1139         // with our children.
1140         setMaxMarginAfterValues(std::max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), std::max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
1141
1142         if (!marginInfo.hasMarginAfterQuirk())
1143             setHasMarginAfterQuirk(false);
1144
1145         if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
1146             // We have no bottom margin and our last child has a quirky margin.
1147             // We will pick up this quirky margin and pass it through.
1148             // This deals with the <td><div><p> case.
1149             setHasMarginAfterQuirk(true);
1150     }
1151 }
1152
1153 void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
1154 {
1155     marginInfo.setAtAfterSideOfBlock(true);
1156
1157     // If we can't collapse with children then go ahead and add in the bottom margin.
1158     if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
1159         && (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
1160         setLogicalHeight(logicalHeight() + marginInfo.margin());
1161         
1162     // Now add in our bottom border/padding.
1163     setLogicalHeight(logicalHeight() + afterSide);
1164
1165     // Negative margins can cause our height to shrink below our minimal height (border/padding).
1166     // If this happens, ensure that the computed height is increased to the minimal height.
1167     setLogicalHeight(std::max(logicalHeight(), beforeSide + afterSide));
1168
1169     // Update our bottom collapsed margin info.
1170     setCollapsedBottomMargin(marginInfo);
1171 }
1172
1173 void RenderBlockFlow::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
1174 {
1175     if (!hasRareBlockFlowData()) {
1176         if (pos == RenderBlockFlowRareData::positiveMarginBeforeDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginBeforeDefault(*this))
1177             return;
1178         materializeRareBlockFlowData();
1179     }
1180
1181     rareBlockFlowData()->m_margins.setPositiveMarginBefore(pos);
1182     rareBlockFlowData()->m_margins.setNegativeMarginBefore(neg);
1183 }
1184
1185 void RenderBlockFlow::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
1186 {
1187     if (!hasRareBlockFlowData()) {
1188         if (pos == RenderBlockFlowRareData::positiveMarginAfterDefault(*this) && neg == RenderBlockFlowRareData::negativeMarginAfterDefault(*this))
1189             return;
1190         materializeRareBlockFlowData();
1191     }
1192
1193     rareBlockFlowData()->m_margins.setPositiveMarginAfter(pos);
1194     rareBlockFlowData()->m_margins.setNegativeMarginAfter(neg);
1195 }
1196
1197 void RenderBlockFlow::setMustDiscardMarginBefore(bool value)
1198 {
1199     if (style().marginBeforeCollapse() == MDISCARD) {
1200         ASSERT(value);
1201         return;
1202     }
1203
1204     if (!hasRareBlockFlowData()) {
1205         if (!value)
1206             return;
1207         materializeRareBlockFlowData();
1208     }
1209
1210     rareBlockFlowData()->m_discardMarginBefore = value;
1211 }
1212
1213 void RenderBlockFlow::setMustDiscardMarginAfter(bool value)
1214 {
1215     if (style().marginAfterCollapse() == MDISCARD) {
1216         ASSERT(value);
1217         return;
1218     }
1219
1220     if (!hasRareBlockFlowData()) {
1221         if (!value)
1222             return;
1223         materializeRareBlockFlowData();
1224     }
1225
1226     rareBlockFlowData()->m_discardMarginAfter = value;
1227 }
1228
1229 bool RenderBlockFlow::mustDiscardMarginBefore() const
1230 {
1231     return style().marginBeforeCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginBefore);
1232 }
1233
1234 bool RenderBlockFlow::mustDiscardMarginAfter() const
1235 {
1236     return style().marginAfterCollapse() == MDISCARD || (hasRareBlockFlowData() && rareBlockFlowData()->m_discardMarginAfter);
1237 }
1238
1239 bool RenderBlockFlow::mustDiscardMarginBeforeForChild(const RenderBox& child) const
1240 {
1241     ASSERT(!child.selfNeedsLayout());
1242     if (!child.isWritingModeRoot())
1243         return child.isRenderBlockFlow() ? toRenderBlockFlow(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1244     if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1245         return child.isRenderBlockFlow() ? toRenderBlockFlow(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1246
1247     // FIXME: We return false here because the implementation is not geometrically complete. We have values only for before/after, not start/end.
1248     // In case the boxes are perpendicular we assume the property is not specified.
1249     return false;
1250 }
1251
1252 bool RenderBlockFlow::mustDiscardMarginAfterForChild(const RenderBox& child) const
1253 {
1254     ASSERT(!child.selfNeedsLayout());
1255     if (!child.isWritingModeRoot())
1256         return child.isRenderBlockFlow() ? toRenderBlockFlow(child).mustDiscardMarginAfter() : (child.style().marginAfterCollapse() == MDISCARD);
1257     if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1258         return child.isRenderBlockFlow() ? toRenderBlockFlow(child).mustDiscardMarginBefore() : (child.style().marginBeforeCollapse() == MDISCARD);
1259
1260     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1261     return false;
1262 }
1263
1264 bool RenderBlockFlow::mustSeparateMarginBeforeForChild(const RenderBox& child) const
1265 {
1266     ASSERT(!child.selfNeedsLayout());
1267     const RenderStyle& childStyle = child.style();
1268     if (!child.isWritingModeRoot())
1269         return childStyle.marginBeforeCollapse() == MSEPARATE;
1270     if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1271         return childStyle.marginAfterCollapse() == MSEPARATE;
1272
1273     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1274     return false;
1275 }
1276
1277 bool RenderBlockFlow::mustSeparateMarginAfterForChild(const RenderBox& child) const
1278 {
1279     ASSERT(!child.selfNeedsLayout());
1280     const RenderStyle& childStyle = child.style();
1281     if (!child.isWritingModeRoot())
1282         return childStyle.marginAfterCollapse() == MSEPARATE;
1283     if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
1284         return childStyle.marginBeforeCollapse() == MSEPARATE;
1285
1286     // FIXME: See |mustDiscardMarginBeforeForChild| above.
1287     return false;
1288 }
1289
1290 static bool inNormalFlow(RenderBox& child)
1291 {
1292     RenderBlock* curr = child.containingBlock();
1293     while (curr && curr != &child.view()) {
1294         if (curr->hasColumns() || curr->isRenderFlowThread())
1295             return true;
1296         if (curr->isFloatingOrOutOfFlowPositioned())
1297             return false;
1298         curr = curr->containingBlock();
1299     }
1300     return true;
1301 }
1302
1303 LayoutUnit RenderBlockFlow::applyBeforeBreak(RenderBox& child, LayoutUnit logicalOffset)
1304 {
1305     // FIXME: Add page break checking here when we support printing.
1306     bool checkColumnBreaks = view().layoutState()->isPaginatingColumns();
1307     bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1308     RenderFlowThread* flowThread = flowThreadContainingBlock();
1309     bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
1310     bool checkBeforeAlways = (checkColumnBreaks && child.style().columnBreakBefore() == PBALWAYS) || (checkPageBreaks && child.style().pageBreakBefore() == PBALWAYS)
1311         || (checkRegionBreaks && child.style().regionBreakBefore() == PBALWAYS);
1312     if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1313         if (checkColumnBreaks)
1314             view().layoutState()->addForcedColumnBreak(&child, logicalOffset);
1315         if (checkRegionBreaks) {
1316             LayoutUnit offsetBreakAdjustment = 0;
1317             if (flowThread->addForcedRegionBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset, &child, true, &offsetBreakAdjustment))
1318                 return logicalOffset + offsetBreakAdjustment;
1319         }
1320         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1321     }
1322     return logicalOffset;
1323 }
1324
1325 LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox& child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
1326 {
1327     // FIXME: Add page break checking here when we support printing.
1328     bool checkColumnBreaks = view().layoutState()->isPaginatingColumns();
1329     bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight; // FIXME: Once columns can print we have to check this.
1330     RenderFlowThread* flowThread = flowThreadContainingBlock();
1331     bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
1332     bool checkAfterAlways = (checkColumnBreaks && child.style().columnBreakAfter() == PBALWAYS) || (checkPageBreaks && child.style().pageBreakAfter() == PBALWAYS)
1333         || (checkRegionBreaks && child.style().regionBreakAfter() == PBALWAYS);
1334     if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
1335         LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1336
1337         // So our margin doesn't participate in the next collapsing steps.
1338         marginInfo.clearMargin();
1339
1340         if (checkColumnBreaks)
1341             view().layoutState()->addForcedColumnBreak(&child, logicalOffset);
1342         if (checkRegionBreaks) {
1343             LayoutUnit offsetBreakAdjustment = 0;
1344             if (flowThread->addForcedRegionBreak(this, offsetFromLogicalTopOfFirstPage() + logicalOffset + marginOffset, &child, false, &offsetBreakAdjustment))
1345                 return logicalOffset + marginOffset + offsetBreakAdjustment;
1346         }
1347         return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
1348     }
1349     return logicalOffset;
1350 }
1351
1352 LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox& child, bool atBeforeSideOfBlock)
1353 {
1354     RenderBlock* childRenderBlock = child.isRenderBlock() ? toRenderBlock(&child) : nullptr;
1355
1356     if (estimateWithoutPagination != logicalTopAfterClear) {
1357         // Our guess prior to pagination movement was wrong. Before we attempt to paginate, let's try again at the new
1358         // position.
1359         setLogicalHeight(logicalTopAfterClear);
1360         setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
1361
1362         if (child.shrinkToAvoidFloats()) {
1363             // The child's width depends on the line width.
1364             // When the child shifts to clear an item, its width can
1365             // change (because it has more available line width).
1366             // So go ahead and mark the item as dirty.
1367             child.setChildNeedsLayout(MarkOnlyThis);
1368         }
1369         
1370         if (childRenderBlock) {
1371             if (!child.avoidsFloats() && childRenderBlock->containsFloats())
1372                 toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
1373             if (!child.needsLayout())
1374                 child.markForPaginationRelayoutIfNeeded();
1375         }
1376
1377         // Our guess was wrong. Make the child lay itself out again.
1378         child.layoutIfNeeded();
1379     }
1380
1381     LayoutUnit oldTop = logicalTopAfterClear;
1382
1383     // If the object has a page or column break value of "before", then we should shift to the top of the next page.
1384     LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
1385
1386     if (pageLogicalHeightForOffset(result)) {
1387         LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
1388         LayoutUnit spaceShortage = child.logicalHeight() - remainingLogicalHeight;
1389         if (spaceShortage > 0) {
1390             // If the child crosses a column boundary, report a break, in case nothing inside it has already
1391             // done so. The column balancer needs to know how much it has to stretch the columns to make more
1392             // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
1393             // This should be improved, though, because here we just pretend that the child is
1394             // unsplittable. A splittable child, on the other hand, has break opportunities at every position
1395             // where there's no child content, border or padding. In other words, we risk stretching more
1396             // than necessary.
1397             setPageBreak(result, spaceShortage);
1398         }
1399     }
1400
1401     // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
1402     LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
1403     LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
1404     
1405     LayoutUnit paginationStrut = 0;
1406     LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
1407     if (unsplittableAdjustmentDelta)
1408         paginationStrut = unsplittableAdjustmentDelta;
1409     else if (childRenderBlock && childRenderBlock->paginationStrut())
1410         paginationStrut = childRenderBlock->paginationStrut();
1411
1412     if (paginationStrut) {
1413         // We are willing to propagate out to our parent block as long as we were at the top of the block prior
1414         // to collapsing our margins, and as long as we didn't clear or move as a result of other pagination.
1415         if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
1416             // FIXME: Should really check if we're exceeding the page height before propagating the strut, but we don't
1417             // have all the information to do so (the strut only has the remaining amount to push). Gecko gets this wrong too
1418             // and pushes to the next page anyway, so not too concerned about it.
1419             setPaginationStrut(result + paginationStrut);
1420             if (childRenderBlock)
1421                 childRenderBlock->setPaginationStrut(0);
1422         } else
1423             result += paginationStrut;
1424     }
1425
1426     // Similar to how we apply clearance. Go ahead and boost height() to be the place where we're going to position the child.
1427     setLogicalHeight(logicalHeight() + (result - oldTop));
1428     
1429     // Return the final adjusted logical top.
1430     return result;
1431 }
1432
1433 static inline LayoutUnit calculateMinimumPageHeight(RenderStyle* renderStyle, RootInlineBox* lastLine, LayoutUnit lineTop, LayoutUnit lineBottom)
1434 {
1435     // We may require a certain minimum number of lines per page in order to satisfy
1436     // orphans and widows, and that may affect the minimum page height.
1437     unsigned lineCount = std::max<unsigned>(renderStyle->hasAutoOrphans() ? 1 : renderStyle->orphans(), renderStyle->hasAutoWidows() ? 1 : renderStyle->widows());
1438     if (lineCount > 1) {
1439         RootInlineBox* line = lastLine;
1440         for (unsigned i = 1; i < lineCount && line->prevRootBox(); i++)
1441             line = line->prevRootBox();
1442
1443         // FIXME: Paginating using line overflow isn't all fine. See FIXME in
1444         // adjustLinePositionForPagination() for more details.
1445         LayoutRect overflow = line->logicalVisualOverflowRect(line->lineTop(), line->lineBottom());
1446         lineTop = std::min(line->lineTopWithLeading(), overflow.y());
1447     }
1448     return lineBottom - lineTop;
1449 }
1450
1451 void RenderBlockFlow::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, RenderFlowThread* flowThread)
1452 {
1453     // FIXME: For now we paginate using line overflow. This ensures that lines don't overlap at all when we
1454     // put a strut between them for pagination purposes. However, this really isn't the desired rendering, since
1455     // the line on the top of the next page will appear too far down relative to the same kind of line at the top
1456     // of the first column.
1457     //
1458     // The rendering we would like to see is one where the lineTopWithLeading is at the top of the column, and any line overflow
1459     // simply spills out above the top of the column. This effect would match what happens at the top of the first column.
1460     // We can't achieve this rendering, however, until we stop columns from clipping to the column bounds (thus allowing
1461     // for overflow to occur), and then cache visible overflow for each column rect.
1462     //
1463     // Furthermore, the paint we have to do when a column has overflow has to be special. We need to exclude
1464     // content that paints in a previous column (and content that paints in the following column).
1465     //
1466     // For now we'll at least honor the lineTopWithLeading when paginating if it is above the logical top overflow. This will
1467     // at least make positive leading work in typical cases.
1468     //
1469     // FIXME: Another problem with simply moving lines is that the available line width may change (because of floats).
1470     // Technically if the location we move the line to has a different line width than our old position, then we need to dirty the
1471     // line and all following lines.
1472     LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
1473     LayoutUnit logicalOffset = std::min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
1474     LayoutUnit logicalBottom = std::max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
1475     LayoutUnit lineHeight = logicalBottom - logicalOffset;
1476     updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(&style(), lineBox, logicalOffset, logicalBottom));
1477     logicalOffset += delta;
1478     lineBox->setPaginationStrut(0);
1479     lineBox->setIsFirstAfterPageBreak(false);
1480     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1481     bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
1482     // If lineHeight is greater than pageLogicalHeight, but logicalVisualOverflow.height() still fits, we are
1483     // still going to add a strut, so that the visible overflow fits on a single page.
1484     if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight)
1485         || !hasNextPage(logicalOffset))
1486         // FIXME: In case the line aligns with the top of the page (or it's slightly shifted downwards) it will not be marked as the first line in the page.
1487         // From here, the fix is not straightforward because it's not easy to always determine when the current line is the first in the page.
1488         return;
1489     LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1490
1491     int lineIndex = lineCount(lineBox);
1492     if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
1493         if (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex) {
1494             clearShouldBreakAtLineToAvoidWidow();
1495             setDidBreakAtLineToAvoidWidow();
1496         }
1497         // If we have a non-uniform page height, then we have to shift further possibly.
1498         if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, lineHeight))
1499             return;
1500         if (lineHeight > pageLogicalHeight) {
1501             // Split the top margin in order to avoid splitting the visible part of the line.
1502             remainingLogicalHeight -= std::min(lineHeight - pageLogicalHeight, std::max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
1503         }
1504         LayoutUnit totalLogicalHeight = lineHeight + std::max<LayoutUnit>(0, logicalOffset);
1505         LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
1506         setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
1507         if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style().hasAutoOrphans() && style().orphans() >= lineIndex))
1508             && !isOutOfFlowPositioned() && !isTableCell())
1509             setPaginationStrut(remainingLogicalHeight + std::max<LayoutUnit>(0, logicalOffset));
1510         else {
1511             delta += remainingLogicalHeight;
1512             lineBox->setPaginationStrut(remainingLogicalHeight);
1513             lineBox->setIsFirstAfterPageBreak(true);
1514         }
1515     } else if (remainingLogicalHeight == pageLogicalHeight && lineBox != firstRootBox())
1516         lineBox->setIsFirstAfterPageBreak(true);
1517 }
1518
1519 void RenderBlockFlow::setBreakAtLineToAvoidWidow(int lineToBreak)
1520 {
1521     ASSERT(lineToBreak >= 0);
1522     ASSERT(!ensureRareBlockFlowData().m_didBreakAtLineToAvoidWidow);
1523     ensureRareBlockFlowData().m_lineBreakToAvoidWidow = lineToBreak;
1524 }
1525
1526 void RenderBlockFlow::setDidBreakAtLineToAvoidWidow()
1527 {
1528     ASSERT(!shouldBreakAtLineToAvoidWidow());
1529     if (!hasRareBlockFlowData())
1530         return;
1531
1532     rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = true;
1533 }
1534
1535 void RenderBlockFlow::clearDidBreakAtLineToAvoidWidow()
1536 {
1537     if (!hasRareBlockFlowData())
1538         return;
1539
1540     rareBlockFlowData()->m_didBreakAtLineToAvoidWidow = false;
1541 }
1542
1543 void RenderBlockFlow::clearShouldBreakAtLineToAvoidWidow() const
1544 {
1545     ASSERT(shouldBreakAtLineToAvoidWidow());
1546     if (!hasRareBlockFlowData())
1547         return;
1548
1549     rareBlockFlowData()->m_lineBreakToAvoidWidow = -1;
1550 }
1551
1552 bool RenderBlockFlow::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
1553 {
1554     if (!shouldBreakAtLineToAvoidWidow())
1555         return false;
1556
1557     statePusher.pop();
1558     setEverHadLayout(true);
1559     layoutBlock(false);
1560     return true;
1561 }
1562
1563 bool RenderBlockFlow::hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1564 {
1565     ASSERT(view().layoutState() && view().layoutState()->isPaginated());
1566
1567     RenderFlowThread* flowThread = flowThreadContainingBlock();
1568     if (!flowThread)
1569         return true; // Printing and multi-column both make new pages to accommodate content.
1570
1571     // See if we're in the last region.
1572     LayoutUnit pageOffset = offsetFromLogicalTopOfFirstPage() + logicalOffset;
1573     RenderRegion* region = flowThread->regionAtBlockOffset(this, pageOffset, this);
1574     if (!region)
1575         return false;
1576     if (region->isLastRegion())
1577         return region->isRenderRegionSet() || region->style().regionFragment() == BreakRegionFragment
1578             || (pageBoundaryRule == IncludePageBoundary && pageOffset == region->logicalTopForFlowThreadContent());
1579     return true;
1580 }
1581
1582 LayoutUnit RenderBlockFlow::adjustForUnsplittableChild(RenderBox& child, LayoutUnit logicalOffset, bool includeMargins)
1583 {
1584     bool checkColumnBreaks = view().layoutState()->isPaginatingColumns();
1585     bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight;
1586     RenderFlowThread* flowThread = flowThreadContainingBlock();
1587     bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
1588     bool isUnsplittable = child.isUnsplittableForPagination() || (checkColumnBreaks && child.style().columnBreakInside() == PBAVOID)
1589         || (checkPageBreaks && child.style().pageBreakInside() == PBAVOID)
1590         || (checkRegionBreaks && child.style().regionBreakInside() == PBAVOID);
1591     if (!isUnsplittable)
1592         return logicalOffset;
1593     LayoutUnit childLogicalHeight = logicalHeightForChild(child) + (includeMargins ? marginBeforeForChild(child) + marginAfterForChild(child) : LayoutUnit());
1594     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1595     bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
1596     updateMinimumPageHeight(logicalOffset, childLogicalHeight);
1597     if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
1598         || !hasNextPage(logicalOffset))
1599         return logicalOffset;
1600     LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
1601     if (remainingLogicalHeight < childLogicalHeight) {
1602         if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, childLogicalHeight))
1603             return logicalOffset;
1604         return logicalOffset + remainingLogicalHeight;
1605     }
1606     return logicalOffset;
1607 }
1608
1609 bool RenderBlockFlow::pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const
1610 {
1611     bool checkRegion = false;
1612     for (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment); pageLogicalHeight;
1613         pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment)) {
1614         if (minimumLogicalHeight <= pageLogicalHeight)
1615             return true;
1616         if (!hasNextPage(logicalOffset + adjustment))
1617             return false;
1618         adjustment += pageLogicalHeight;
1619         checkRegion = true;
1620     }
1621     return !checkRegion;
1622 }
1623
1624 void RenderBlockFlow::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
1625 {
1626     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1627         flowThread->setPageBreak(this, offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
1628 }
1629
1630 void RenderBlockFlow::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
1631 {
1632     if (RenderFlowThread* flowThread = flowThreadContainingBlock())
1633         flowThread->updateMinimumPageHeight(this, offsetFromLogicalTopOfFirstPage() + offset, minHeight);
1634     else if (ColumnInfo* colInfo = view().layoutState()->m_columnInfo)
1635         colInfo->updateMinimumColumnHeight(minHeight);
1636 }
1637
1638 LayoutUnit RenderBlockFlow::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
1639 {
1640     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
1641     if (!pageLogicalHeight)
1642         return logicalOffset;
1643     
1644     // The logicalOffset is in our coordinate space.  We can add in our pushed offset.
1645     LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
1646     if (pageBoundaryRule == ExcludePageBoundary)
1647         return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
1648     return logicalOffset + remainingLogicalHeight;
1649 }
1650
1651 LayoutUnit RenderBlockFlow::pageLogicalTopForOffset(LayoutUnit offset) const
1652 {
1653     LayoutUnit firstPageLogicalTop = isHorizontalWritingMode() ? view().layoutState()->m_pageOffset.height() : view().layoutState()->m_pageOffset.width();
1654     LayoutUnit blockLogicalTop = isHorizontalWritingMode() ? view().layoutState()->m_layoutOffset.height() : view().layoutState()->m_layoutOffset.width();
1655
1656     LayoutUnit cumulativeOffset = offset + blockLogicalTop;
1657     RenderFlowThread* flowThread = flowThreadContainingBlock();
1658     if (!flowThread) {
1659         LayoutUnit pageLogicalHeight = view().layoutState()->pageLogicalHeight();
1660         if (!pageLogicalHeight)
1661             return 0;
1662         return cumulativeOffset - roundToInt(cumulativeOffset - firstPageLogicalTop) % roundToInt(pageLogicalHeight);
1663     }
1664     return flowThread->pageLogicalTopForOffset(cumulativeOffset);
1665 }
1666
1667 LayoutUnit RenderBlockFlow::pageLogicalHeightForOffset(LayoutUnit offset) const
1668 {
1669     RenderFlowThread* flowThread = flowThreadContainingBlock();
1670     if (!flowThread)
1671         return view().layoutState()->m_pageLogicalHeight;
1672     return flowThread->pageLogicalHeightForOffset(offset + offsetFromLogicalTopOfFirstPage());
1673 }
1674
1675 LayoutUnit RenderBlockFlow::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
1676 {
1677     offset += offsetFromLogicalTopOfFirstPage();
1678     
1679     RenderFlowThread* flowThread = flowThreadContainingBlock();
1680     if (!flowThread) {
1681         LayoutUnit pageLogicalHeight = view().layoutState()->m_pageLogicalHeight;
1682         LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight);
1683         if (pageBoundaryRule == IncludePageBoundary) {
1684             // If includeBoundaryPoint is true the line exactly on the top edge of a
1685             // column will act as being part of the previous column.
1686             remainingHeight = intMod(remainingHeight, pageLogicalHeight);
1687         }
1688         return remainingHeight;
1689     }
1690     
1691     return flowThread->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule);
1692 }
1693
1694
1695 void RenderBlockFlow::layoutLineGridBox()
1696 {
1697     if (style().lineGrid() == RenderStyle::initialLineGrid()) {
1698         setLineGridBox(0);
1699         return;
1700     }
1701     
1702     setLineGridBox(0);
1703
1704     auto lineGridBox = std::make_unique<RootInlineBox>(*this);
1705     lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
1706     lineGridBox->setConstructed();
1707     GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1708     VerticalPositionCache verticalPositionCache;
1709     lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
1710     
1711     setLineGridBox(std::move(lineGridBox));
1712
1713     // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
1714     // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping
1715     // to this grid.
1716 }
1717
1718 bool RenderBlockFlow::containsFloat(RenderBox& renderer) const
1719 {
1720     return m_floatingObjects && m_floatingObjects->set().contains<RenderBox&, FloatingObjectHashTranslator>(renderer);
1721 }
1722
1723 void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
1724 {
1725     RenderBlock::styleDidChange(diff, oldStyle);
1726     
1727     // After our style changed, if we lose our ability to propagate floats into next sibling
1728     // blocks, then we need to find the top most parent containing that overhanging float and
1729     // then mark its descendants with floats for layout and clear all floats from its next
1730     // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
1731     bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
1732     if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
1733         RenderBlockFlow* parentBlock = this;
1734         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1735
1736         auto ancestors = ancestorsOfType<RenderBlockFlow>(*this);
1737         for (auto ancestor = ancestors.begin(), end = ancestors.end(); ancestor != end; ++ancestor) {
1738             if (ancestor->isRenderView())
1739                 break;
1740             if (ancestor->hasOverhangingFloats()) {
1741                 for (auto it = floatingObjectSet.begin(), end = floatingObjectSet.end(); it != end; ++it) {
1742                     RenderBox& renderer = (*it)->renderer();
1743                     if (ancestor->hasOverhangingFloat(renderer)) {
1744                         parentBlock = &*ancestor;
1745                         break;
1746                     }
1747                 }
1748             }
1749         }
1750
1751         parentBlock->markAllDescendantsWithFloatsForLayout();
1752         parentBlock->markSiblingsWithFloatsForLayout();
1753     }
1754
1755     if (auto fragment = renderNamedFlowFragment())
1756         fragment->setStyle(RenderNamedFlowFragment::createStyle(style()));
1757
1758     if (diff >= StyleDifferenceRepaint)
1759         invalidateLineLayoutPath();
1760 }
1761
1762 void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
1763 {
1764     const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
1765     s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
1766
1767     if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle.position()) {
1768         if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle.hasOutOfFlowPosition())
1769             markAllDescendantsWithFloatsForLayout();
1770     }
1771
1772     RenderBlock::styleWillChange(diff, newStyle);
1773 }
1774
1775 void RenderBlockFlow::deleteLines()
1776 {
1777     if (containsFloats())
1778         m_floatingObjects->clearLineBoxTreePointers();
1779
1780     if (m_simpleLineLayout) {
1781         ASSERT(!m_lineBoxes.firstLineBox());
1782         m_simpleLineLayout = nullptr;
1783     } else
1784         m_lineBoxes.deleteLineBoxTree();
1785
1786     RenderBlock::deleteLines();
1787 }
1788
1789 void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1790 {
1791     RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
1792     moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
1793
1794     // When a portion of the render tree is being detached, anonymous blocks
1795     // will be combined as their children are deleted. In this process, the
1796     // anonymous block later in the tree is merged into the one preceeding it.
1797     // It can happen that the later block (this) contains floats that the
1798     // previous block (toBlockFlow) did not contain, and thus are not in the
1799     // floating objects list for toBlockFlow. This can result in toBlockFlow
1800     // containing floats that are not in it's floating objects list, but are in
1801     // the floating objects lists of siblings and parents. This can cause
1802     // problems when the float itself is deleted, since the deletion code
1803     // assumes that if a float is not in it's containing block's floating
1804     // objects list, it isn't in any floating objects list. In order to
1805     // preserve this condition (removing it has serious performance
1806     // implications), we need to copy the floating objects from the old block
1807     // (this) to the new block (toBlockFlow). The float's metrics will likely
1808     // all be wrong, but since toBlockFlow is already marked for layout, this
1809     // will get fixed before anything gets displayed.
1810     // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
1811     if (m_floatingObjects) {
1812         if (!toBlockFlow->m_floatingObjects)
1813             toBlockFlow->createFloatingObjects();
1814
1815         const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1816         auto end = fromFloatingObjectSet.end();
1817
1818         for (auto it = fromFloatingObjectSet.begin(); it != end; ++it) {
1819             FloatingObject* floatingObject = it->get();
1820
1821             // Don't insert the object again if it's already in the list
1822             if (toBlockFlow->containsFloat(floatingObject->renderer()))
1823                 continue;
1824
1825             toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
1826         }
1827     }
1828 }
1829
1830 void RenderBlockFlow::addOverflowFromFloats()
1831 {
1832     if (!m_floatingObjects)
1833         return;
1834
1835     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1836     auto end = floatingObjectSet.end();
1837     for (auto it = floatingObjectSet.begin(); it != end; ++it) {
1838         FloatingObject* r = it->get();
1839         if (r->isDescendant())
1840             addOverflowFromChild(&r->renderer(), IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1841     }
1842 }
1843
1844 void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1845 {
1846     RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
1847
1848     if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1849         addOverflowFromFloats();
1850 }
1851
1852 void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
1853 {
1854     // Repaint any overhanging floats (if we know we're the one to paint them).
1855     // Otherwise, bail out.
1856     if (!hasOverhangingFloats())
1857         return;
1858
1859     // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
1860     // in this block. Better yet would be to push extra state for the containers of other floats.
1861     LayoutStateDisabler layoutStateDisabler(&view());
1862     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1863     auto end = floatingObjectSet.end();
1864     for (auto it = floatingObjectSet.begin(); it != end; ++it) {
1865         FloatingObject* floatingObject = it->get();
1866         // Only repaint the object if it is overhanging, is not in its own layer, and
1867         // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
1868         // condition is replaced with being a descendant of us.
1869         if (logicalBottomForFloat(floatingObject) > logicalHeight()
1870             && !floatingObject->renderer().hasSelfPaintingLayer()
1871             && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer().isDescendantOf(this)))) {
1872             floatingObject->renderer().repaint();
1873             floatingObject->renderer().repaintOverhangingFloats(false);
1874         }
1875     }
1876 }
1877
1878 void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
1879 {
1880     if (!m_floatingObjects)
1881         return;
1882
1883     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1884     auto end = floatingObjectSet.end();
1885     for (auto it = floatingObjectSet.begin(); it != end; ++it) {
1886         FloatingObject* r = it->get();
1887         // Only paint the object if our m_shouldPaint flag is set.
1888         if (r->shouldPaint() && !r->renderer().hasSelfPaintingLayer()) {
1889             PaintInfo currentPaintInfo(paintInfo);
1890             currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
1891             // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
1892             LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->renderer().x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->renderer().y()));
1893             r->renderer().paint(currentPaintInfo, childPoint);
1894             if (!preservePhase) {
1895                 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
1896                 r->renderer().paint(currentPaintInfo, childPoint);
1897                 currentPaintInfo.phase = PaintPhaseFloat;
1898                 r->renderer().paint(currentPaintInfo, childPoint);
1899                 currentPaintInfo.phase = PaintPhaseForeground;
1900                 r->renderer().paint(currentPaintInfo, childPoint);
1901                 currentPaintInfo.phase = PaintPhaseOutline;
1902                 r->renderer().paint(currentPaintInfo, childPoint);
1903             }
1904         }
1905     }
1906 }
1907
1908 void RenderBlockFlow::clipOutFloatingObjects(RenderBlock& rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
1909 {
1910     if (m_floatingObjects) {
1911         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1912         auto end = floatingObjectSet.end();
1913         for (auto it = floatingObjectSet.begin(); it != end; ++it) {
1914             FloatingObject* floatingObject = it->get();
1915             LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
1916                 offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
1917                 floatingObject->renderer().width(), floatingObject->renderer().height());
1918             rootBlock.flipForWritingMode(floatBox);
1919             floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
1920             paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
1921         }
1922     }
1923 }
1924
1925 void RenderBlockFlow::createFloatingObjects()
1926 {
1927     m_floatingObjects = adoptPtr(new FloatingObjects(*this));
1928 }
1929
1930 void RenderBlockFlow::removeFloatingObjects()
1931 {
1932     if (!m_floatingObjects)
1933         return;
1934
1935     m_floatingObjects->clear();
1936 }
1937
1938 FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox& floatBox)
1939 {
1940     ASSERT(floatBox.isFloating());
1941
1942     // Create the list of special objects if we don't aleady have one
1943     if (!m_floatingObjects)
1944         createFloatingObjects();
1945     else {
1946         // Don't insert the floatingObject again if it's already in the list
1947         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1948         auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
1949         if (it != floatingObjectSet.end())
1950             return it->get();
1951     }
1952
1953     // Create the special floatingObject entry & append it to the list
1954
1955     std::unique_ptr<FloatingObject> floatingObject = FloatingObject::create(floatBox);
1956     
1957     // Our location is irrelevant if we're unsplittable or no pagination is in effect.
1958     // Just go ahead and lay out the float.
1959     bool isChildRenderBlock = floatBox.isRenderBlock();
1960     if (isChildRenderBlock && !floatBox.needsLayout() && view().layoutState()->pageLogicalHeightChanged())
1961         floatBox.setChildNeedsLayout(MarkOnlyThis);
1962             
1963     bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view().layoutState()->needsBlockDirectionLocationSetBeforeLayout();
1964     if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
1965         floatBox.layoutIfNeeded();
1966     else {
1967         floatBox.updateLogicalWidth();
1968         floatBox.computeAndSetBlockDirectionMargins(this);
1969     }
1970
1971     setLogicalWidthForFloat(floatingObject.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
1972
1973     return m_floatingObjects->add(std::move(floatingObject));
1974 }
1975
1976 void RenderBlockFlow::removeFloatingObject(RenderBox& floatBox)
1977 {
1978     if (m_floatingObjects) {
1979         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1980         auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(floatBox);
1981         if (it != floatingObjectSet.end()) {
1982             FloatingObject* floatingObject = it->get();
1983             if (childrenInline()) {
1984                 LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
1985                 LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
1986
1987                 // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
1988                 if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
1989                     logicalBottom = LayoutUnit::max();
1990                 else {
1991                     // Special-case zero- and less-than-zero-height floats: those don't touch
1992                     // the line that they're on, but it still needs to be dirtied. This is
1993                     // accomplished by pretending they have a height of 1.
1994                     logicalBottom = std::max(logicalBottom, logicalTop + 1);
1995                 }
1996                 if (floatingObject->originatingLine()) {
1997                     if (!selfNeedsLayout()) {
1998                         ASSERT(&floatingObject->originatingLine()->renderer() == this);
1999                         floatingObject->originatingLine()->markDirty();
2000                     }
2001 #if !ASSERT_DISABLED
2002                     floatingObject->setOriginatingLine(0);
2003 #endif
2004                 }
2005                 markLinesDirtyInBlockRange(0, logicalBottom);
2006             }
2007             m_floatingObjects->remove(floatingObject);
2008         }
2009     }
2010 }
2011
2012 void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
2013 {
2014     if (!containsFloats())
2015         return;
2016     
2017     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2018     FloatingObject* curr = floatingObjectSet.last().get();
2019     while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
2020         m_floatingObjects->remove(curr);
2021         if (floatingObjectSet.isEmpty())
2022             break;
2023         curr = floatingObjectSet.last().get();
2024     }
2025 }
2026
2027 LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2028 {
2029     LayoutUnit offset = fixedOffset;
2030     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2031         offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2032     return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
2033 }
2034
2035 LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
2036 {
2037     LayoutUnit offset = fixedOffset;
2038     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2039         offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
2040     return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
2041 }
2042
2043 LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
2044 {
2045     RenderBox& childBox = floatingObject->renderer();
2046     LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2047     LayoutUnit logicalRightOffset; // Constant part of right offset.
2048 #if ENABLE(CSS_SHAPES)
2049     // FIXME Bug 102948: This only works for shape outside directly set on this block.
2050     ShapeInsideInfo* shapeInsideInfo = this->layoutShapeInsideInfo();
2051     // FIXME: Implement behavior for right floats.
2052     if (shapeInsideInfo) {
2053         LayoutSize floatLogicalSize = logicalSizeForFloat(floatingObject);
2054         // floatingObject's logicalSize doesn't contain the actual height at this point, so we need to calculate it
2055         floatLogicalSize.setHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2056
2057         // FIXME: If the float doesn't fit in the shape we should push it under the content box
2058         logicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(floatLogicalSize);
2059         if (logicalHeight() > logicalTopOffset)
2060             logicalTopOffset = logicalHeight();
2061
2062         SegmentList segments = shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, floatLogicalSize.height());
2063         // FIXME Bug 102949: Add support for shapes with multiple segments.
2064         if (segments.size() == 1) {
2065             // The segment offsets are relative to the content box.
2066             logicalRightOffset = logicalLeftOffset + segments[0].logicalRight;
2067             logicalLeftOffset += segments[0].logicalLeft;
2068         }
2069     } else
2070 #endif
2071         logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
2072
2073     LayoutUnit floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
2074
2075     LayoutUnit floatLogicalLeft;
2076
2077     bool insideFlowThread = flowThreadContainingBlock();
2078
2079     if (childBox.style().floating() == LeftFloat) {
2080         LayoutUnit heightRemainingLeft = 1;
2081         LayoutUnit heightRemainingRight = 1;
2082         floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2083         while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
2084             logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2085             floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
2086             if (insideFlowThread) {
2087                 // Have to re-evaluate all of our offsets, since they may have changed.
2088                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2089                 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2090                 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2091             }
2092         }
2093         floatLogicalLeft = std::max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
2094     } else {
2095         LayoutUnit heightRemainingLeft = 1;
2096         LayoutUnit heightRemainingRight = 1;
2097         floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2098         while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
2099             logicalTopOffset += std::min(heightRemainingLeft, heightRemainingRight);
2100             floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
2101             if (insideFlowThread) {
2102                 // Have to re-evaluate all of our offsets, since they may have changed.
2103                 logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
2104                 logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
2105                 floatLogicalWidth = std::min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
2106             }
2107         }
2108         // Use the original width of the float here, since the local variable
2109         // |floatLogicalWidth| was capped to the available line width. See
2110         // fast/block/float/clamped-right-float.html.
2111         floatLogicalLeft -= logicalWidthForFloat(floatingObject);
2112     }
2113     
2114     return LayoutPoint(floatLogicalLeft, logicalTopOffset);
2115 }
2116
2117 bool RenderBlockFlow::positionNewFloats()
2118 {
2119     if (!m_floatingObjects)
2120         return false;
2121
2122     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2123     if (floatingObjectSet.isEmpty())
2124         return false;
2125
2126     // If all floats have already been positioned, then we have no work to do.
2127     if (floatingObjectSet.last()->isPlaced())
2128         return false;
2129
2130     // Move backwards through our floating object list until we find a float that has
2131     // already been positioned. Then we'll be able to move forward, positioning all of
2132     // the new floats that need it.
2133     auto it = floatingObjectSet.end();
2134     --it; // Go to last item.
2135     auto begin = floatingObjectSet.begin();
2136     FloatingObject* lastPlacedFloatingObject = 0;
2137     while (it != begin) {
2138         --it;
2139         if ((*it)->isPlaced()) {
2140             lastPlacedFloatingObject = it->get();
2141             ++it;
2142             break;
2143         }
2144     }
2145
2146     LayoutUnit logicalTop = logicalHeight();
2147     
2148     // The float cannot start above the top position of the last positioned float.
2149     if (lastPlacedFloatingObject)
2150         logicalTop = std::max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
2151
2152     auto end = floatingObjectSet.end();
2153     // Now walk through the set of unpositioned floats and place them.
2154     for (; it != end; ++it) {
2155         FloatingObject* floatingObject = it->get();
2156         // The containing block is responsible for positioning floats, so if we have floats in our
2157         // list that come from somewhere else, do not attempt to position them.
2158         if (floatingObject->renderer().containingBlock() != this)
2159             continue;
2160
2161         RenderBox& childBox = floatingObject->renderer();
2162
2163         LayoutUnit childLogicalLeftMargin = style().isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
2164
2165         LayoutRect oldRect = childBox.frameRect();
2166
2167         if (childBox.style().clear() & CLEFT)
2168             logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
2169         if (childBox.style().clear() & CRIGHT)
2170             logicalTop = std::max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
2171
2172         LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
2173
2174         setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2175
2176         setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2177         setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2178
2179         estimateRegionRangeForBoxChild(childBox);
2180
2181         LayoutState* layoutState = view().layoutState();
2182         bool isPaginated = layoutState->isPaginated();
2183         if (isPaginated && !childBox.needsLayout())
2184             childBox.markForPaginationRelayoutIfNeeded();
2185         
2186         childBox.layoutIfNeeded();
2187
2188         if (isPaginated) {
2189             // If we are unsplittable and don't fit, then we need to move down.
2190             // We include our margins as part of the unsplittable area.
2191             LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
2192             
2193             // See if we have a pagination strut that is making us move down further.
2194             // Note that an unsplittable child can't also have a pagination strut, so this is
2195             // exclusive with the case above.
2196             RenderBlock* childBlock = childBox.isRenderBlock() ? toRenderBlock(&childBox) : nullptr;
2197             if (childBlock && childBlock->paginationStrut()) {
2198                 newLogicalTop += childBlock->paginationStrut();
2199                 childBlock->setPaginationStrut(0);
2200             }
2201             
2202             if (newLogicalTop != floatLogicalLocation.y()) {
2203                 floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
2204
2205                 floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
2206                 setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
2207
2208                 setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
2209                 setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
2210         
2211                 if (childBlock)
2212                     childBlock->setChildNeedsLayout(MarkOnlyThis);
2213                 childBox.layoutIfNeeded();
2214             }
2215
2216             if (updateRegionRangeForBoxChild(childBox)) {
2217                 childBox.setNeedsLayout(MarkOnlyThis);
2218                 childBox.layoutIfNeeded();
2219             }
2220         }
2221
2222         setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
2223
2224         setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
2225
2226         m_floatingObjects->addPlacedObject(floatingObject);
2227
2228 #if ENABLE(CSS_SHAPES)
2229         if (ShapeOutsideInfo* shapeOutside = childBox.shapeOutsideInfo())
2230             shapeOutside->setShapeSize(logicalWidthForChild(childBox), logicalHeightForChild(childBox));
2231 #endif
2232         // If the child moved, we have to repaint it.
2233         if (childBox.checkForRepaintDuringLayout())
2234             childBox.repaintDuringLayoutIfMoved(oldRect);
2235     }
2236     return true;
2237 }
2238
2239 void RenderBlockFlow::newLine(EClear clear)
2240 {
2241     positionNewFloats();
2242     // set y position
2243     LayoutUnit newY = 0;
2244     switch (clear) {
2245     case CLEFT:
2246         newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2247         break;
2248     case CRIGHT:
2249         newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2250         break;
2251     case CBOTH:
2252         newY = lowestFloatLogicalBottom();
2253     default:
2254         break;
2255     }
2256     if (height() < newY)
2257         setLogicalHeight(newY);
2258 }
2259
2260 LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2261 {
2262     if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
2263         return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
2264
2265     return fixedOffset;
2266 }
2267
2268 LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
2269 {
2270     if (m_floatingObjects && m_floatingObjects->hasRightObjects())
2271         return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
2272
2273     return fixedOffset;
2274 }
2275
2276 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight) const
2277 {
2278     if (!m_floatingObjects)
2279         return logicalHeight;
2280
2281     return m_floatingObjects->findNextFloatLogicalBottomBelow(logicalHeight);
2282 }
2283
2284 LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelowForBlock(LayoutUnit logicalHeight) const
2285 {
2286     if (!m_floatingObjects)
2287         return logicalHeight;
2288
2289     return m_floatingObjects->findNextFloatLogicalBottomBelowForBlock(logicalHeight);
2290 }
2291
2292 LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
2293 {
2294     if (!m_floatingObjects)
2295         return 0;
2296     LayoutUnit lowestFloatBottom = 0;
2297     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2298     auto end = floatingObjectSet.end();
2299     for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2300         FloatingObject* floatingObject = it->get();
2301         if (floatingObject->isPlaced() && floatingObject->type() & floatType)
2302             lowestFloatBottom = std::max(lowestFloatBottom, logicalBottomForFloat(floatingObject));
2303     }
2304     return lowestFloatBottom;
2305 }
2306
2307 LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow& child, bool makeChildPaintOtherFloats)
2308 {
2309     // Prevent floats from being added to the canvas by the root element, e.g., <html>.
2310     if (child.hasOverflowClip() || !child.containsFloats() || child.isRoot() || child.hasColumns() || child.isWritingModeRoot())
2311         return 0;
2312
2313     LayoutUnit childLogicalTop = child.logicalTop();
2314     LayoutUnit childLogicalLeft = child.logicalLeft();
2315     LayoutUnit lowestFloatLogicalBottom = 0;
2316
2317     // Floats that will remain the child's responsibility to paint should factor into its
2318     // overflow.
2319     auto childEnd = child.m_floatingObjects->set().end();
2320     for (auto childIt = child.m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
2321         FloatingObject* floatingObject = childIt->get();
2322         LayoutUnit floatLogicalBottom = std::min(logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
2323         LayoutUnit logicalBottom = childLogicalTop + floatLogicalBottom;
2324         lowestFloatLogicalBottom = std::max(lowestFloatLogicalBottom, logicalBottom);
2325
2326         if (logicalBottom > logicalHeight()) {
2327             // If the object is not in the list, we add it now.
2328             if (!containsFloat(floatingObject->renderer())) {
2329                 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
2330                 bool shouldPaint = false;
2331
2332                 // The nearest enclosing layer always paints the float (so that zindex and stacking
2333                 // behaves properly). We always want to propagate the desire to paint the float as
2334                 // far out as we can, to the outermost block that overlaps the float, stopping only
2335                 // if we hit a self-painting layer boundary.
2336                 if (floatingObject->renderer().enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
2337                     floatingObject->setShouldPaint(false);
2338                     shouldPaint = true;
2339                 }
2340                 // We create the floating object list lazily.
2341                 if (!m_floatingObjects)
2342                     createFloatingObjects();
2343
2344                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
2345             }
2346         } else {
2347             if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer().hasSelfPaintingLayer()
2348                 && floatingObject->renderer().isDescendantOf(&child) && floatingObject->renderer().enclosingFloatPaintingLayer() == child.enclosingFloatPaintingLayer()) {
2349                 // The float is not overhanging from this block, so if it is a descendant of the child, the child should
2350                 // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
2351                 // layer.
2352                 // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
2353                 // it should paint.
2354                 floatingObject->setShouldPaint(true);
2355             }
2356             
2357             // 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
2358             // child now.
2359             if (floatingObject->isDescendant())
2360                 child.addOverflowFromChild(&floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
2361         }
2362     }
2363     return lowestFloatLogicalBottom;
2364 }
2365
2366 bool RenderBlockFlow::hasOverhangingFloat(RenderBox& renderer)
2367 {
2368     if (!m_floatingObjects || hasColumns() || !parent())
2369         return false;
2370
2371     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2372     auto it = floatingObjectSet.find<RenderBox&, FloatingObjectHashTranslator>(renderer);
2373     if (it == floatingObjectSet.end())
2374         return false;
2375
2376     return logicalBottomForFloat(it->get()) > logicalHeight();
2377 }
2378
2379 void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
2380 {
2381     ASSERT(!avoidsFloats());
2382
2383     // If the parent or previous sibling doesn't have any floats to add, don't bother.
2384     if (!prev->m_floatingObjects)
2385         return;
2386
2387     logicalLeftOffset += marginLogicalLeft();
2388
2389     const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
2390     auto prevEnd = prevSet.end();
2391     for (auto prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
2392         FloatingObject* floatingObject = prevIt->get();
2393         if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
2394             if (!m_floatingObjects || !m_floatingObjects->set().contains<FloatingObject&, FloatingObjectHashTranslator>(*floatingObject)) {
2395                 // We create the floating object list lazily.
2396                 if (!m_floatingObjects)
2397                     createFloatingObjects();
2398
2399                 // Applying the child's margin makes no sense in the case where the child was passed in.
2400                 // since this margin was added already through the modification of the |logicalLeftOffset| variable
2401                 // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
2402                 // into account. Only apply this code if prev is the parent, since otherwise the left margin
2403                 // will get applied twice.
2404                 LayoutSize offset = isHorizontalWritingMode()
2405                     ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
2406                     : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
2407
2408                 m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
2409             }
2410         }
2411     }
2412 }
2413
2414 void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
2415 {
2416     if (!everHadLayout() && !containsFloats())
2417         return;
2418
2419     MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
2420     setChildNeedsLayout(markParents);
2421
2422     if (floatToRemove)
2423         removeFloatingObject(*floatToRemove);
2424
2425     // Iterate over our children and mark them as needed.
2426     if (!childrenInline()) {
2427         for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
2428             if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
2429                 continue;
2430             if (!child->isRenderBlockFlow()) {
2431                 RenderBlock* childBlock = toRenderBlock(child);
2432                 if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
2433                     childBlock->setChildNeedsLayout(markParents);
2434                 continue;
2435             }
2436             RenderBlockFlow* childBlock = toRenderBlockFlow(child);
2437             if ((floatToRemove ? childBlock->containsFloat(*floatToRemove) : childBlock->containsFloats()) || childBlock->shrinkToAvoidFloats())
2438                 childBlock->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
2439         }
2440     }
2441 }
2442
2443 void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
2444 {
2445     if (!m_floatingObjects)
2446         return;
2447
2448     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2449     auto end = floatingObjectSet.end();
2450
2451     for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
2452         if (!next->isRenderBlockFlow() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
2453             continue;
2454
2455         RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
2456         for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2457             RenderBox& floatingBox = (*it)->renderer();
2458             if (floatToRemove && &floatingBox != floatToRemove)
2459                 continue;
2460             if (nextBlock->containsFloat(floatingBox))
2461                 nextBlock->markAllDescendantsWithFloatsForLayout(&floatingBox);
2462         }
2463     }
2464 }
2465
2466 LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
2467 {
2468     if (!style().isFlippedBlocksWritingMode())
2469         return point;
2470     
2471     // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
2472     // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
2473     // case.
2474     if (isHorizontalWritingMode())
2475         return LayoutPoint(point.x(), point.y() + height() - child->renderer().height() - 2 * yPositionForFloatIncludingMargin(child));
2476     return LayoutPoint(point.x() + width() - child->renderer().width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
2477 }
2478
2479 LayoutUnit RenderBlockFlow::getClearDelta(RenderBox& child, LayoutUnit logicalTop)
2480 {
2481     // There is no need to compute clearance if we have no floats.
2482     if (!containsFloats())
2483         return 0;
2484     
2485     // At least one float is present. We need to perform the clearance computation.
2486     bool clearSet = child.style().clear() != CNONE;
2487     LayoutUnit logicalBottom = 0;
2488     switch (child.style().clear()) {
2489     case CNONE:
2490         break;
2491     case CLEFT:
2492         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
2493         break;
2494     case CRIGHT:
2495         logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
2496         break;
2497     case CBOTH:
2498         logicalBottom = lowestFloatLogicalBottom();
2499         break;
2500     }
2501
2502     // 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).
2503     LayoutUnit result = clearSet ? std::max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
2504     if (!result && child.avoidsFloats()) {
2505         LayoutUnit newLogicalTop = logicalTop;
2506         while (true) {
2507             LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
2508             if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
2509                 return newLogicalTop - logicalTop;
2510
2511             RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
2512             LayoutRect borderBox = child.borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
2513             LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2514
2515             // FIXME: None of this is right for perpendicular writing-mode children.
2516             LayoutUnit childOldLogicalWidth = child.logicalWidth();
2517             LayoutUnit childOldMarginLeft = child.marginLeft();
2518             LayoutUnit childOldMarginRight = child.marginRight();
2519             LayoutUnit childOldLogicalTop = child.logicalTop();
2520
2521             child.setLogicalTop(newLogicalTop);
2522             child.updateLogicalWidth();
2523             region = regionAtBlockOffset(logicalTopForChild(child));
2524             borderBox = child.borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
2525             LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
2526
2527             child.setLogicalTop(childOldLogicalTop);
2528             child.setLogicalWidth(childOldLogicalWidth);
2529             child.setMarginLeft(childOldMarginLeft);
2530             child.setMarginRight(childOldMarginRight);
2531             
2532             if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
2533                 // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
2534                 // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
2535                 // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
2536                 if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
2537                     child.setChildNeedsLayout(MarkOnlyThis);
2538                 return newLogicalTop - logicalTop;
2539             }
2540
2541             newLogicalTop = nextFloatLogicalBottomBelowForBlock(newLogicalTop);
2542             ASSERT(newLogicalTop >= logicalTop);
2543             if (newLogicalTop < logicalTop)
2544                 break;
2545         }
2546         ASSERT_NOT_REACHED();
2547     }
2548     return result;
2549 }
2550
2551 bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
2552 {
2553     if (!m_floatingObjects)
2554         return false;
2555
2556     LayoutPoint adjustedLocation = accumulatedOffset;
2557     if (isRenderView())
2558         adjustedLocation += toLayoutSize(toRenderView(*this).frameView().scrollPosition());
2559
2560     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2561     auto begin = floatingObjectSet.begin();
2562     for (auto it = floatingObjectSet.end(); it != begin;) {
2563         --it;
2564         FloatingObject* floatingObject = it->get();
2565         if (floatingObject->shouldPaint() && !floatingObject->renderer().hasSelfPaintingLayer()) {
2566             LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer().x();
2567             LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer().y();
2568             LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
2569             if (floatingObject->renderer().hitTest(request, result, locationInContainer, childPoint)) {
2570                 updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
2571                 return true;
2572             }
2573         }
2574     }
2575
2576     return false;
2577 }
2578
2579 bool RenderBlockFlow::hitTestInlineChildren(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2580 {
2581     ASSERT(childrenInline());
2582
2583     if (m_simpleLineLayout)
2584         return SimpleLineLayout::hitTestFlow(*this, *m_simpleLineLayout, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2585
2586     return m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction);
2587 }
2588
2589 void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
2590 {
2591     if (style().visibility() != VISIBLE)
2592         return;
2593
2594     // We don't deal with relative positioning.  Our assumption is that you shrink to fit the lines without accounting
2595     // for either overflow or translations via relative positioning.
2596     if (childrenInline()) {
2597         const_cast<RenderBlockFlow&>(*this).ensureLineBoxes();
2598
2599         for (auto box = firstRootBox(); box; box = box->nextRootBox()) {
2600             if (box->firstChild())
2601                 left = std::min(left, x + static_cast<LayoutUnit>(box->firstChild()->x()));
2602             if (box->lastChild())
2603                 right = std::max(right, x + static_cast<LayoutUnit>(ceilf(box->lastChild()->logicalRight())));
2604         }
2605     } else {
2606         for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
2607             if (!obj->isFloatingOrOutOfFlowPositioned()) {
2608                 if (obj->isRenderBlockFlow() && !obj->hasOverflowClip())
2609                     toRenderBlockFlow(obj)->adjustForBorderFit(x + obj->x(), left, right);
2610                 else if (obj->style().visibility() == VISIBLE) {
2611                     // We are a replaced element or some kind of non-block-flow object.
2612                     left = std::min(left, x + obj->x());
2613                     right = std::max(right, x + obj->x() + obj->width());
2614                 }
2615             }
2616         }
2617     }
2618
2619     if (m_floatingObjects) {
2620         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2621         auto end = floatingObjectSet.end();
2622         for (auto it = floatingObjectSet.begin(); it != end; ++it) {
2623             FloatingObject* r = it->get();
2624             // Only examine the object if our m_shouldPaint flag is set.
2625             if (r->shouldPaint()) {
2626                 LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->renderer().x();
2627                 LayoutUnit floatRight = floatLeft + r->renderer().width();
2628                 left = std::min(left, floatLeft);
2629                 right = std::max(right, floatRight);
2630             }
2631         }
2632     }
2633 }
2634
2635 void RenderBlockFlow::fitBorderToLinesIfNeeded()
2636 {
2637     if (style().borderFit() == BorderFitBorder || hasOverrideWidth())
2638         return;
2639
2640     // Walk any normal flow lines to snugly fit.
2641     LayoutUnit left = LayoutUnit::max();
2642     LayoutUnit right = LayoutUnit::min();
2643     LayoutUnit oldWidth = contentWidth();
2644     adjustForBorderFit(0, left, right);
2645     
2646     // Clamp to our existing edges. We can never grow. We only shrink.
2647     LayoutUnit leftEdge = borderLeft() + paddingLeft();
2648     LayoutUnit rightEdge = leftEdge + oldWidth;
2649     left = std::min(rightEdge, std::max(leftEdge, left));
2650     right = std::max(leftEdge, std::min(rightEdge, right));
2651     
2652     LayoutUnit newContentWidth = right - left;
2653     if (newContentWidth == oldWidth)
2654         return;
2655     
2656     setOverrideLogicalContentWidth(newContentWidth);
2657     layoutBlock(false);
2658     clearOverrideLogicalContentWidth();
2659 }
2660
2661 void RenderBlockFlow::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
2662 {
2663     if (logicalTop >= logicalBottom)
2664         return;
2665
2666     RootInlineBox* lowestDirtyLine = lastRootBox();
2667     RootInlineBox* afterLowest = lowestDirtyLine;
2668     while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < LayoutUnit::max()) {
2669         afterLowest = lowestDirtyLine;
2670         lowestDirtyLine = lowestDirtyLine->prevRootBox();
2671     }
2672
2673     while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
2674         afterLowest->markDirty();
2675         afterLowest = afterLowest->prevRootBox();
2676     }
2677 }
2678
2679 int RenderBlockFlow::firstLineBaseline() const
2680 {
2681     if (isWritingModeRoot() && !isRubyRun())
2682         return -1;
2683
2684     if (!childrenInline())
2685         return RenderBlock::firstLineBaseline();
2686
2687     if (!hasLines())
2688         return -1;
2689
2690     if (m_simpleLineLayout)
2691         return SimpleLineLayout::computeFlowFirstLineBaseline(*this, *m_simpleLineLayout);
2692
2693     ASSERT(firstRootBox());
2694     return firstRootBox()->logicalTop() + firstLineStyle().fontMetrics().ascent(firstRootBox()->baselineType());
2695 }
2696
2697 int RenderBlockFlow::inlineBlockBaseline(LineDirectionMode lineDirection) const
2698 {
2699     if (isWritingModeRoot() && !isRubyRun())
2700         return -1;
2701
2702     if (!childrenInline())
2703         return RenderBlock::inlineBlockBaseline(lineDirection);
2704
2705     if (!hasLines()) {
2706         if (!hasLineIfEmpty())
2707             return -1;
2708         const FontMetrics& fontMetrics = firstLineStyle().fontMetrics();
2709         return fontMetrics.ascent()
2710              + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
2711              + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
2712     }
2713
2714     if (m_simpleLineLayout)
2715         return SimpleLineLayout::computeFlowLastLineBaseline(*this, *m_simpleLineLayout);
2716
2717     bool isFirstLine = lastRootBox() == firstRootBox();
2718     const RenderStyle& style = isFirstLine ? firstLineStyle() : this->style();
2719     return lastRootBox()->logicalTop() + style.fontMetrics().ascent(lastRootBox()->baselineType());
2720 }
2721
2722 GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2723     LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
2724 {
2725     ASSERT(!m_simpleLineLayout);
2726
2727     GapRects result;
2728
2729     bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
2730
2731     if (!hasLines()) {
2732         if (containsStart) {
2733             // Go ahead and update our lastLogicalTop to be the bottom of the block.  <hr>s or empty blocks with height can trip this
2734             // case.
2735             lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
2736             lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
2737             lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
2738         }
2739         return result;
2740     }
2741
2742     RootInlineBox* lastSelectedLine = 0;
2743     RootInlineBox* curr;
2744     for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
2745
2746     // Now paint the gaps for the lines.
2747     for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
2748         LayoutUnit selTop =  curr->selectionTopAdjustedForPrecedingBlock();
2749         LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
2750
2751         if (!containsStart && !lastSelectedLine &&
2752             selectionState() != SelectionStart && selectionState() != SelectionBoth)
2753             result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, selTop, cache, paintInfo));
2754         
2755         LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
2756         logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
2757         LayoutRect physicalRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
2758         if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
2759             || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
2760             result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, cache, paintInfo));
2761
2762         lastSelectedLine = curr;
2763     }
2764
2765     if (containsStart && !lastSelectedLine)
2766         // VisibleSelection must start just after our last line.
2767         lastSelectedLine = lastRootBox();
2768
2769     if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
2770         // Go ahead and update our lastY to be the bottom of the last selected line.
2771         lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
2772         lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
2773         lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
2774     }
2775     return result;
2776 }
2777
2778 void RenderBlockFlow::createRenderNamedFlowFragmentIfNeeded()
2779 {
2780     if (!document().cssRegionsEnabled() || renderNamedFlowFragment() || isRenderNamedFlowFragment())
2781         return;
2782
2783     if (style().isDisplayRegionType() && style().hasFlowFrom()) {
2784         RenderNamedFlowFragment* flowFragment = new RenderNamedFlowFragment(document(), RenderNamedFlowFragment::createStyle(style()));
2785         flowFragment->initializeStyle();
2786         setRenderNamedFlowFragment(flowFragment);
2787         addChild(renderNamedFlowFragment());
2788     }
2789 }
2790
2791 bool RenderBlockFlow::canHaveChildren() const
2792 {
2793     return !renderNamedFlowFragment() ? RenderBlock::canHaveChildren() : renderNamedFlowFragment()->canHaveChildren();
2794 }
2795
2796 bool RenderBlockFlow::canHaveGeneratedChildren() const
2797 {
2798     return !renderNamedFlowFragment() ? RenderBlock::canHaveGeneratedChildren() : renderNamedFlowFragment()->canHaveGeneratedChildren();
2799 }
2800
2801 bool RenderBlockFlow::namedFlowFragmentNeedsUpdate() const
2802 {
2803     if (!isRenderNamedFlowFragmentContainer())
2804         return false;
2805
2806     return hasRelativeLogicalHeight() && !isRenderView();
2807 }
2808
2809 void RenderBlockFlow::updateLogicalHeight()
2810 {
2811     RenderBlock::updateLogicalHeight();
2812
2813     if (renderNamedFlowFragment())
2814         renderNamedFlowFragment()->setLogicalHeight(std::max<LayoutUnit>(0, logicalHeight() - borderAndPaddingLogicalHeight()));
2815 }
2816
2817 void RenderBlockFlow::setRenderNamedFlowFragment(RenderNamedFlowFragment* flowFragment)
2818 {
2819     RenderBlockFlowRareData& rareData = ensureRareBlockFlowData();
2820     if (rareData.m_renderNamedFlowFragment)
2821         rareData.m_renderNamedFlowFragment->destroy();
2822     rareData.m_renderNamedFlowFragment = flowFragment;
2823 }
2824
2825 static bool shouldCheckLines(RenderObject& obj)
2826 {
2827     return !obj.isFloatingOrOutOfFlowPositioned() && !obj.isRunIn() && obj.isRenderBlockFlow() && obj.style().height().isAuto() && (!obj.isDeprecatedFlexibleBox() || obj.style().boxOrient() == VERTICAL);
2828 }
2829
2830 RootInlineBox* RenderBlockFlow::lineAtIndex(int i) const
2831 {
2832     ASSERT(i >= 0);
2833
2834     if (style().visibility() != VISIBLE)
2835         return nullptr;
2836
2837     if (childrenInline()) {
2838         for (auto box = firstRootBox(); box; box = box->nextRootBox()) {
2839             if (!i--)
2840                 return box;
2841         }
2842     } else {
2843         for (auto child = firstChild(); child; child = child->nextSibling()) {
2844             if (!shouldCheckLines(*child))
2845                 continue;
2846             if (RootInlineBox* box = toRenderBlockFlow(child)->lineAtIndex(i))
2847                 return box;
2848         }
2849     }
2850
2851     return nullptr;
2852 }
2853
2854 int RenderBlockFlow::lineCount(const RootInlineBox* stopRootInlineBox, bool* found) const
2855 {
2856     if (style().visibility() != VISIBLE)
2857         return 0;
2858
2859     int count = 0;
2860
2861     if (childrenInline()) {
2862         for (auto box = firstRootBox(); box; box = box->nextRootBox()) {
2863             count++;
2864             if (box == stopRootInlineBox) {
2865                 if (found)
2866                     *found = true;
2867                 break;
2868             }
2869         }
2870     } else {
2871         for (auto child = firstChild(); child; child = child->nextSibling()) {
2872             if (shouldCheckLines(*child)) {
2873                 bool recursiveFound = false;
2874                 count += toRenderBlockFlow(child)->lineCount(stopRootInlineBox, &recursiveFound);
2875                 if (recursiveFound) {
2876                     if (found)
2877                         *found = true;
2878                     break;
2879                 }
2880             }
2881         }
2882     }
2883
2884     return count;
2885 }
2886
2887 static int getHeightForLineCount(const RenderBlockFlow& block, int lineCount, bool includeBottom, int& count)
2888 {
2889     if (block.style().visibility() != VISIBLE)
2890         return -1;
2891
2892     if (block.childrenInline()) {
2893         for (auto box = block.firstRootBox(); box; box = box->nextRootBox()) {
2894             if (++count == lineCount)
2895                 return box->lineBottom() + (includeBottom ? (block.borderBottom() + block.paddingBottom()) : LayoutUnit());
2896         }
2897     } else {
2898         RenderBox* normalFlowChildWithoutLines = 0;
2899         for (auto obj = block.firstChildBox(); obj; obj = obj->nextSiblingBox()) {
2900             if (shouldCheckLines(*obj)) {
2901                 int result = getHeightForLineCount(toRenderBlockFlow(*obj), lineCount, false, count);
2902                 if (result != -1)
2903                     return result + obj->y() + (includeBottom ? (block.borderBottom() + block.paddingBottom()) : LayoutUnit());
2904             } else if (!obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn())
2905                 normalFlowChildWithoutLines = obj;
2906         }
2907         if (normalFlowChildWithoutLines && !lineCount)
2908             return normalFlowChildWithoutLines->y() + normalFlowChildWithoutLines->height();
2909     }
2910     
2911     return -1;
2912 }
2913
2914 int RenderBlockFlow::heightForLineCount(int lineCount)
2915 {
2916     int count = 0;
2917     return getHeightForLineCount(*this, lineCount, true, count);
2918 }
2919
2920 void RenderBlockFlow::clearTruncation()
2921 {
2922     if (style().visibility() != VISIBLE)
2923         return;
2924
2925     if (childrenInline() && hasMarkupTruncation()) {
2926         ensureLineBoxes();
2927
2928         setHasMarkupTruncation(false);
2929         for (auto box = firstRootBox(); box; box = box->nextRootBox())
2930             box->clearTruncation();
2931     } else {
2932         for (auto child = firstChild(); child; child = child->nextSibling()) {
2933             if (shouldCheckLines(*child))
2934                 toRenderBlockFlow(child)->clearTruncation();
2935         }
2936     }
2937 }
2938
2939 bool RenderBlockFlow::containsNonZeroBidiLevel() const
2940 {
2941     for (auto root = firstRootBox(); root; root = root->nextRootBox()) {
2942         for (auto box = root->firstLeafChild(); box; box = box->nextLeafChild()) {
2943             if (box->bidiLevel())
2944                 return true;
2945         }
2946     }
2947     return false;
2948 }
2949
2950 Position RenderBlockFlow::positionForBox(InlineBox *box, bool start) const
2951 {
2952     if (!box)
2953         return Position();
2954
2955     if (!box->renderer().nonPseudoNode())
2956         return createLegacyEditingPosition(nonPseudoElement(), start ? caretMinOffset() : caretMaxOffset());
2957
2958     if (!box->isInlineTextBox())
2959         return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? box->renderer().caretMinOffset() : box->renderer().caretMaxOffset());
2960
2961     InlineTextBox* textBox = toInlineTextBox(box);
2962     return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? textBox->start() : textBox->start() + textBox->len());
2963 }
2964
2965 VisiblePosition RenderBlockFlow::positionForPointWithInlineChildren(const LayoutPoint& pointInLogicalContents)
2966 {
2967     ASSERT(childrenInline());
2968
2969     ensureLineBoxes();
2970
2971     if (!firstRootBox())
2972         return createVisiblePosition(0, DOWNSTREAM);
2973
2974     bool linesAreFlipped = style().isFlippedLinesWritingMode();
2975     bool blocksAreFlipped = style().isFlippedBlocksWritingMode();
2976
2977     // look for the closest line box in the root box which is at the passed-in y coordinate
2978     InlineBox* closestBox = 0;
2979     RootInlineBox* firstRootBoxWithChildren = 0;
2980     RootInlineBox* lastRootBoxWithChildren = 0;
2981     for (RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox()) {
2982         if (!root->firstLeafChild())
2983             continue;
2984         if (!firstRootBoxWithChildren)
2985             firstRootBoxWithChildren = root;
2986
2987         if (!linesAreFlipped && root->isFirstAfterPageBreak() && (pointInLogicalContents.y() < root->lineTopWithLeading()
2988             || (blocksAreFlipped && pointInLogicalContents.y() == root->lineTopWithLeading())))
2989             break;
2990
2991         lastRootBoxWithChildren = root;
2992
2993         // check if this root line box is located at this y coordinate
2994         if (pointInLogicalContents.y() < root->selectionBottom() || (blocksAreFlipped && pointInLogicalContents.y() == root->selectionBottom())) {
2995             if (linesAreFlipped) {
2996                 RootInlineBox* nextRootBoxWithChildren = root->nextRootBox();
2997                 while (nextRootBoxWithChildren && !nextRootBoxWithChildren->firstLeafChild())
2998                     nextRootBoxWithChildren = nextRootBoxWithChildren->nextRootBox();
2999
3000                 if (nextRootBoxWithChildren && nextRootBoxWithChildren->isFirstAfterPageBreak() && (pointInLogicalContents.y() > nextRootBoxWithChildren->lineTopWithLeading()
3001                     || (!blocksAreFlipped && pointInLogicalContents.y() == nextRootBoxWithChildren->lineTopWithLeading())))
3002                     continue;
3003             }
3004             closestBox = root->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
3005             if (closestBox)
3006                 break;
3007         }
3008     }
3009
3010     bool moveCaretToBoundary = frame().editor().behavior().shouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom();
3011
3012     if (!moveCaretToBoundary && !closestBox && lastRootBoxWithChildren) {
3013         // y coordinate is below last root line box, pretend we hit it
3014         closestBox = lastRootBoxWithChildren->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
3015     }
3016
3017     if (closestBox) {
3018         if (moveCaretToBoundary) {
3019             LayoutUnit firstRootBoxWithChildrenTop = std::min<LayoutUnit>(firstRootBoxWithChildren->selectionTop(), firstRootBoxWithChildren->logicalTop());
3020             if (pointInLogicalContents.y() < firstRootBoxWithChildrenTop
3021                 || (blocksAreFlipped && pointInLogicalContents.y() == firstRootBoxWithChildrenTop)) {
3022                 InlineBox* box = firstRootBoxWithChildren->firstLeafChild();
3023                 if (box->isLineBreak()) {
3024                     if (InlineBox* newBox = box->nextLeafChildIgnoringLineBreak())
3025                         box = newBox;
3026                 }
3027                 // y coordinate is above first root line box, so return the start of the first
3028                 return VisiblePosition(positionForBox(box, true), DOWNSTREAM);
3029             }
3030         }
3031
3032         // pass the box a top position that is inside it
3033         LayoutPoint point(pointInLogicalContents.x(), closestBox->root().blockDirectionPointInLine());
3034         if (!isHorizontalWritingMode())
3035             point = point.transposedPoint();
3036         if (closestBox->renderer().isReplaced())
3037             return positionForPointRespectingEditingBoundaries(*this, toRenderBox(closestBox->renderer()), point);
3038         return closestBox->renderer().positionForPoint(point);
3039     }
3040
3041     if (lastRootBoxWithChildren) {
3042         // We hit this case for Mac behavior when the Y coordinate is below the last box.
3043         ASSERT(moveCaretToBoundary);
3044         InlineBox* logicallyLastBox;
3045         if (lastRootBoxWithChildren->getLogicalEndBoxWithNode(logicallyLastBox))
3046             return VisiblePosition(positionForBox(logicallyLastBox, false), DOWNSTREAM);
3047     }
3048
3049     // Can't reach this. We have a root line box, but it has no kids.
3050     // FIXME: This should ASSERT_NOT_REACHED(), but clicking on placeholder text
3051     // seems to hit this code path.
3052     return createVisiblePosition(0, DOWNSTREAM);
3053 }
3054
3055 VisiblePosition RenderBlockFlow::positionForPoint(const LayoutPoint& point)
3056 {
3057     if (auto fragment = renderNamedFlowFragment())
3058         return fragment->positionForPoint(point);
3059     return RenderBlock::positionForPoint(point);
3060 }
3061
3062
3063 void RenderBlockFlow::addFocusRingRectsForInlineChildren(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject*)
3064 {
3065     ASSERT(childrenInline());
3066
3067     ensureLineBoxes();
3068
3069     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
3070         LayoutUnit top = std::max<LayoutUnit>(curr->lineTop(), curr->top());
3071         LayoutUnit bottom = std::min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
3072         LayoutRect rect(additionalOffset.x() + curr->x(), additionalOffset.y() + top, curr->width(), bottom - top);
3073         if (!rect.isEmpty())
3074             rects.append(pixelSnappedIntRect(rect));
3075     }
3076 }
3077
3078 void RenderBlockFlow::paintInlineChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3079 {
3080     ASSERT(childrenInline());
3081
3082     if (m_simpleLineLayout) {
3083         SimpleLineLayout::paintFlow(*this, *m_simpleLineLayout, paintInfo, paintOffset);
3084         return;
3085     }
3086     m_lineBoxes.paint(this, paintInfo, paintOffset);
3087 }
3088
3089 bool RenderBlockFlow::relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer& statePusher)
3090 {
3091     if (!hasColumns())
3092         return false;
3093
3094     OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
3095     if (childrenInline())
3096         addOverflowFromInlineChildren();
3097     else
3098         addOverflowFromBlockChildren();
3099     LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderAndPaddingBefore();
3100
3101     // FIXME: We don't balance properly at all in the presence of forced page breaks.  We need to understand what
3102     // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
3103     ColumnInfo* colInfo = columnInfo();
3104     if (!hasSpecifiedPageLogicalHeight) {
3105         LayoutUnit columnHeight = pageLogicalHeight;
3106         int minColumnCount = colInfo->forcedBreaks() + 1;
3107         int desiredColumnCount = colInfo->desiredColumnCount();
3108         if (minColumnCount >= desiredColumnCount) {
3109             // The forced page breaks are in control of the balancing.  Just set the column height to the
3110             // maximum page break distance.
3111             if (!pageLogicalHeight) {
3112                 LayoutUnit distanceBetweenBreaks = std::max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
3113                     view().layoutState()->pageLogicalOffset(this, borderAndPaddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
3114                 columnHeight = std::max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
3115             }
3116         } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
3117             // Now that we know the intrinsic height of the columns, we have to rebalance them.
3118             columnHeight = std::max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
3119         }
3120         
3121         if (columnHeight && columnHeight != pageLogicalHeight) {
3122             statePusher.pop();
3123             setEverHadLayout(true);
3124             layoutBlock(false, columnHeight);
3125             return true;
3126         }
3127     } 
3128
3129     if (pageLogicalHeight)
3130         colInfo->setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
3131
3132     if (columnCount(colInfo)) {
3133         setLogicalHeight(borderAndPaddingBefore() + colInfo->columnHeight() + borderAndPaddingAfter() + scrollbarLogicalHeight());
3134         clearOverflow();
3135     } else
3136         m_overflow = savedOverflow.release();
3137     
3138     return false;
3139 }
3140
3141 bool RenderBlockFlow::hasLines() const
3142 {
3143     ASSERT(childrenInline());
3144
3145     if (m_simpleLineLayout)
3146         return m_simpleLineLayout->lineCount();
3147
3148     return lineBoxes().firstLineBox();
3149 }
3150
3151 void RenderBlockFlow::layoutSimpleLines(LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
3152 {
3153     ASSERT(!m_lineBoxes.firstLineBox());
3154
3155     m_simpleLineLayout = SimpleLineLayout::create(*this);
3156
3157     LayoutUnit lineLayoutHeight = SimpleLineLayout::computeFlowHeight(*this, *m_simpleLineLayout);
3158     LayoutUnit lineLayoutTop = borderAndPaddingBefore();
3159
3160     repaintLogicalTop = lineLayoutTop;
3161     repaintLogicalBottom = lineLayoutTop + lineLayoutHeight;
3162
3163     setLogicalHeight(lineLayoutTop + lineLayoutHeight + borderAndPaddingAfter());
3164 }
3165
3166 void RenderBlockFlow::deleteLineBoxesBeforeSimpleLineLayout()
3167 {
3168     ASSERT(m_lineLayoutPath == SimpleLinesPath);
3169     lineBoxes().deleteLineBoxes();
3170     toRenderText(firstChild())->deleteLineBoxesBeforeSimpleLineLayout();
3171 }
3172
3173 void RenderBlockFlow::ensureLineBoxes()
3174 {
3175     m_lineLayoutPath = ForceLineBoxesPath;
3176
3177     if (!m_simpleLineLayout)
3178         return;
3179     m_simpleLineLayout = nullptr;
3180
3181 #if !ASSERT_DISABLED
3182     LayoutUnit oldHeight = logicalHeight();
3183 #endif
3184     bool didNeedLayout = needsLayout();
3185
3186     bool relayoutChildren = false;
3187     LayoutUnit repaintLogicalTop;
3188     LayoutUnit repaintLogicalBottom;
3189     layoutLineBoxes(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
3190
3191     updateLogicalHeight();
3192     ASSERT(didNeedLayout || logicalHeight() == oldHeight);
3193
3194     if (!didNeedLayout)
3195         clearNeedsLayout();
3196 }
3197
3198 #ifndef NDEBUG
3199 void RenderBlockFlow::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj) const
3200 {
3201     RenderBlock::showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj);
3202     for (const RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox())
3203         root->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, 1);
3204 }
3205 #endif
3206
3207 RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareBlockFlowData()
3208 {
3209     if (hasRareBlockFlowData())
3210         return *m_rareBlockFlowData;
3211     materializeRareBlockFlowData();
3212     return *m_rareBlockFlowData;
3213 }
3214
3215 void RenderBlockFlow::materializeRareBlockFlowData()
3216 {
3217     ASSERT(!hasRareBlockFlowData());
3218     m_rareBlockFlowData = std::make_unique<RenderBlockFlow::RenderBlockFlowRareData>(*this);
3219 }
3220
3221 }
3222 // namespace WebCore