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