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