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