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