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