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, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6 * Copyright (C) Research In Motion Limited 2010. All rights reserved.
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.
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.
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.
25 #include "RenderBlock.h"
27 #include "AXObjectCache.h"
28 #include "ColumnInfo.h"
32 #include "FloatQuad.h"
34 #include "FrameSelection.h"
35 #include "FrameView.h"
36 #include "GraphicsContext.h"
37 #include "HTMLNames.h"
38 #include "HitTestLocation.h"
39 #include "HitTestResult.h"
40 #include "InlineIterator.h"
41 #include "InlineTextBox.h"
42 #include "LayoutRepainter.h"
43 #include "LogicalSelectionOffsetCaches.h"
44 #include "OverflowEvent.h"
46 #include "PaintInfo.h"
47 #include "RenderBoxRegionInfo.h"
48 #include "RenderCombineText.h"
49 #include "RenderDeprecatedFlexibleBox.h"
50 #include "RenderFlexibleBox.h"
51 #include "RenderInline.h"
52 #include "RenderLayer.h"
53 #include "RenderMarquee.h"
54 #include "RenderNamedFlowThread.h"
55 #include "RenderRegion.h"
56 #include "RenderTableCell.h"
57 #include "RenderTextFragment.h"
58 #include "RenderTheme.h"
59 #include "RenderView.h"
60 #include "SVGTextRunRenderingContext.h"
62 #include "ShadowRoot.h"
63 #include "TransformState.h"
64 #include <wtf/StackStats.h>
65 #include <wtf/TemporaryChange.h>
67 #if ENABLE(CSS_SHAPES)
68 #include "ShapeInsideInfo.h"
69 #include "ShapeOutsideInfo.h"
74 using namespace Unicode;
78 using namespace HTMLNames;
80 struct SameSizeAsRenderBlock : public RenderBox {
82 RenderObjectChildList children;
83 RenderLineBoxList lineBoxes;
87 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
89 struct SameSizeAsFloatingObject {
93 uint32_t bitfields : 8;
96 COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
98 struct SameSizeAsMarginInfo {
99 uint32_t bitfields : 16;
100 LayoutUnit margins[2];
103 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
104 static ColumnInfoMap* gColumnInfoMap = 0;
106 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
107 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
109 static TrackedContainerMap* gPositionedContainerMap = 0;
110 static TrackedContainerMap* gPercentHeightContainerMap = 0;
112 typedef WTF::HashMap<RenderBlock*, OwnPtr<ListHashSet<RenderInline*> > > ContinuationOutlineTableMap;
114 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
115 static int gDelayUpdateScrollInfo = 0;
116 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
118 static bool gColumnFlowSplitEnabled = true;
120 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
122 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
123 // only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
124 class OverflowEventDispatcher {
125 WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
127 OverflowEventDispatcher(const RenderBlock* block)
129 , m_hadHorizontalLayoutOverflow(false)
130 , m_hadVerticalLayoutOverflow(false)
132 m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
133 if (m_shouldDispatchEvent) {
134 m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
135 m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
139 ~OverflowEventDispatcher()
141 if (!m_shouldDispatchEvent)
144 bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
145 bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
147 bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
148 bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
149 if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
150 if (FrameView* frameView = m_block->document()->view())
151 frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
156 const RenderBlock* m_block;
157 bool m_shouldDispatchEvent;
158 bool m_hadHorizontalLayoutOverflow;
159 bool m_hadVerticalLayoutOverflow;
162 // Our MarginInfo state used when laying out block children.
163 RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
164 : m_atBeforeSideOfBlock(true)
165 , m_atAfterSideOfBlock(false)
166 , m_hasMarginBeforeQuirk(false)
167 , m_hasMarginAfterQuirk(false)
168 , m_determinedMarginBeforeQuirk(false)
169 , m_discardMargin(false)
171 RenderStyle* blockStyle = block->style();
172 ASSERT(block->isRenderView() || block->parent());
173 m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
174 && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
175 && !block->isRenderFlowThread() && !block->isWritingModeRoot() && !block->parent()->isFlexibleBox()
176 && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
178 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
180 // If any height other than auto is specified in CSS, then we don't collapse our bottom
181 // margins with our children's margins. To do otherwise would be to risk odd visual
182 // effects when the children overflow out of the parent block and yet still collapse
183 // with it. We also don't collapse if we have any bottom border/padding.
184 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
185 (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
187 m_quirkContainer = block->isTableCell() || block->isBody();
189 m_discardMargin = m_canCollapseMarginBeforeWithChildren && block->mustDiscardMarginBefore();
191 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxPositiveMarginBefore() : LayoutUnit();
192 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxNegativeMarginBefore() : LayoutUnit();
195 // -------------------------------------------------------------------------------------------------------
197 RenderBlock::RenderBlock(ContainerNode* node)
200 , m_hasMarginBeforeQuirk(false)
201 , m_hasMarginAfterQuirk(false)
202 , m_beingDestroyed(false)
203 , m_hasMarkupTruncation(false)
204 , m_hasBorderOrPaddingLogicalWidthChanged(false)
206 setChildrenInline(true);
207 COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
208 COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
211 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
213 if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
214 TrackedRendererListHashSet::iterator end = descendantSet->end();
215 for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
216 TrackedContainerMap::iterator it = containerMap->find(*descendant);
217 ASSERT(it != containerMap->end());
218 if (it == containerMap->end())
220 HashSet<RenderBlock*>* containerSet = it->value.get();
221 ASSERT(containerSet->contains(block));
222 containerSet->remove(block);
223 if (containerSet->isEmpty())
224 containerMap->remove(it);
229 RenderBlock::~RenderBlock()
231 if (m_floatingObjects)
232 deleteAllValues(m_floatingObjects->set());
235 gColumnInfoMap->take(this);
237 if (gPercentHeightDescendantsMap)
238 removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
239 if (gPositionedDescendantsMap)
240 removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
243 RenderBlock* RenderBlock::createAnonymous(Document* document)
245 RenderBlock* renderer = new (document->renderArena()) RenderBlock(0);
246 renderer->setDocumentForAnonymous(document);
250 void RenderBlock::willBeDestroyed()
252 // Mark as being destroyed to avoid trouble with merges in removeChild().
253 m_beingDestroyed = true;
255 if (!documentBeingDestroyed()) {
256 if (firstChild() && firstChild()->isRunIn())
257 moveRunInToOriginalPosition(firstChild());
260 // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
261 // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
262 children()->destroyLeftoverChildren();
264 // Destroy our continuation before anything other than anonymous children.
265 // The reason we don't destroy it before anonymous children is that they may
266 // have continuations of their own that are anonymous children of our continuation.
267 RenderBoxModelObject* continuation = this->continuation();
269 continuation->destroy();
273 if (!documentBeingDestroyed()) {
274 if (firstLineBox()) {
275 // We can't wait for RenderBox::destroy to clear the selection,
276 // because by then we will have nuked the line boxes.
277 // FIXME: The FrameSelection should be responsible for this when it
278 // is notified of DOM mutations.
279 if (isSelectionBorder())
280 view()->clearSelection();
282 // If we are an anonymous block, then our line boxes might have children
283 // that will outlast this block. In the non-anonymous block case those
284 // children will be destroyed by the time we return from this function.
285 if (isAnonymousBlock()) {
286 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
287 while (InlineBox* childBox = box->firstChild())
292 parent()->dirtyLinesFromChangedChild(this);
295 m_lineBoxes.deleteLineBoxes(renderArena());
298 lineGridBox()->destroy(renderArena());
300 if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
301 gDelayedUpdateScrollInfoSet->remove(this);
303 RenderBox::willBeDestroyed();
306 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
308 RenderStyle* oldStyle = style();
309 s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
311 setReplaced(newStyle->isDisplayInlineType());
313 if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()) {
314 if (newStyle->position() == StaticPosition)
315 // Clear our positioned objects list. Our absolutely positioned descendants will be
316 // inserted into our containing block's positioned objects list during layout.
317 removePositionedObjects(0, NewContainingBlock);
318 else if (oldStyle->position() == StaticPosition) {
319 // Remove our absolutely positioned descendants from their current containing block.
320 // They will be inserted into our positioned objects list during layout.
321 RenderObject* cb = parent();
322 while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
323 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
324 cb = cb->containingBlock();
330 if (cb->isRenderBlock())
331 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
334 if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
335 markAllDescendantsWithFloatsForLayout();
338 RenderBox::styleWillChange(diff, newStyle);
341 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
343 if (newStyle->isHorizontalWritingMode())
344 return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
345 || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
346 || oldStyle->paddingLeft() != newStyle->paddingLeft()
347 || oldStyle->paddingRight() != newStyle->paddingRight();
349 return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
350 || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
351 || oldStyle->paddingTop() != newStyle->paddingTop()
352 || oldStyle->paddingBottom() != newStyle->paddingBottom();
355 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
357 RenderBox::styleDidChange(diff, oldStyle);
359 RenderStyle* newStyle = style();
361 #if ENABLE(CSS_SHAPES)
362 updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
365 if (!isAnonymousBlock()) {
366 // Ensure that all of our continuation blocks pick up the new style.
367 for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
368 RenderBoxModelObject* nextCont = currCont->continuation();
369 currCont->setContinuation(0);
370 currCont->setStyle(newStyle);
371 currCont->setContinuation(nextCont);
375 propagateStyleToAnonymousChildren(true);
378 // After our style changed, if we lose our ability to propagate floats into next sibling
379 // blocks, then we need to find the top most parent containing that overhanging float and
380 // then mark its descendants with floats for layout and clear all floats from its next
381 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
382 bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
383 if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
384 RenderBlock* parentBlock = this;
385 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
386 FloatingObjectSetIterator end = floatingObjectSet.end();
388 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
389 if (curr->isRenderBlock()) {
390 RenderBlock* currBlock = toRenderBlock(curr);
392 if (currBlock->hasOverhangingFloats()) {
393 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
394 RenderBox* renderer = (*it)->renderer();
395 if (currBlock->hasOverhangingFloat(renderer)) {
396 parentBlock = currBlock;
404 parentBlock->markAllDescendantsWithFloatsForLayout();
405 parentBlock->markSiblingsWithFloatsForLayout();
408 // It's possible for our border/padding to change, but for the overall logical width of the block to
409 // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
410 m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
413 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
415 if (beforeChild && beforeChild->parent() == this)
418 RenderBlock* curr = toRenderBlock(continuation());
419 RenderBlock* nextToLast = this;
420 RenderBlock* last = this;
422 if (beforeChild && beforeChild->parent() == curr) {
423 if (curr->firstChild() == beforeChild)
430 curr = toRenderBlock(curr->continuation());
433 if (!beforeChild && !last->firstChild())
438 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
440 RenderBlock* flow = continuationBefore(beforeChild);
441 ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
442 RenderBoxModelObject* beforeChildParent = 0;
444 beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
446 RenderBoxModelObject* cont = flow->continuation();
448 beforeChildParent = cont;
450 beforeChildParent = flow;
453 if (newChild->isFloatingOrOutOfFlowPositioned()) {
454 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
458 // A continuation always consists of two potential candidates: a block or an anonymous
459 // column span box holding column span children.
460 bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
461 bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
462 bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
464 if (flow == beforeChildParent) {
465 flow->addChildIgnoringContinuation(newChild, beforeChild);
469 // The goal here is to match up if we can, so that we can coalesce and create the
470 // minimal # of continuations needed for the inline.
471 if (childIsNormal == bcpIsNormal) {
472 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
475 if (flowIsNormal == childIsNormal) {
476 flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
479 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
483 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
485 ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
487 // The goal is to locate a suitable box in which to place our child.
488 RenderBlock* beforeChildParent = 0;
490 RenderObject* curr = beforeChild;
491 while (curr && curr->parent() != this)
492 curr = curr->parent();
493 beforeChildParent = toRenderBlock(curr);
494 ASSERT(beforeChildParent);
495 ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
497 beforeChildParent = toRenderBlock(lastChild());
499 // If the new child is floating or positioned it can just go in that block.
500 if (newChild->isFloatingOrOutOfFlowPositioned()) {
501 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
505 // See if the child can be placed in the box.
506 bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
507 bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
509 if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
510 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
515 // Create a new block of the correct type.
516 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
517 children()->appendChildNode(this, newBox);
518 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
522 RenderObject* immediateChild = beforeChild;
523 bool isPreviousBlockViable = true;
524 while (immediateChild->parent() != this) {
525 if (isPreviousBlockViable)
526 isPreviousBlockViable = !immediateChild->previousSibling();
527 immediateChild = immediateChild->parent();
529 if (isPreviousBlockViable && immediateChild->previousSibling()) {
530 toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
534 // Split our anonymous blocks.
535 RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
538 // Create a new anonymous box of the appropriate type.
539 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
540 children()->insertChildNode(this, newBox, newBeforeChild);
541 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
545 RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
547 RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
548 for (RenderObject* curr = this; curr; curr = curr->parent()) {
549 if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
550 || curr->isInlineBlockOrInlineTable())
553 // FIXME: Tables, RenderButtons, and RenderListItems all do special management
554 // of their children that breaks when the flow is split through them. Disabling
555 // multi-column for them to avoid this problem.
556 if (curr->isTable() || curr->isRenderButton() || curr->isListItem())
559 RenderBlock* currBlock = toRenderBlock(curr);
560 if (!currBlock->createsAnonymousWrapper())
561 firstChildIgnoringAnonymousWrappers = currBlock;
563 if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
564 return firstChildIgnoringAnonymousWrappers;
566 if (currBlock->isAnonymousColumnSpanBlock())
572 RenderBlock* RenderBlock::clone() const
574 RenderBlock* cloneBlock;
575 if (isAnonymousBlock()) {
576 cloneBlock = createAnonymousBlock();
577 cloneBlock->setChildrenInline(childrenInline());
580 RenderObject* cloneRenderer = toElement(node())->createRenderer(renderArena(), style());
581 cloneBlock = toRenderBlock(cloneRenderer);
582 cloneBlock->setStyle(style());
584 // This takes care of setting the right value of childrenInline in case
585 // generated content is added to cloneBlock and 'this' does not have
586 // generated content added yet.
587 cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
589 cloneBlock->setFlowThreadState(flowThreadState());
593 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
594 RenderBlock* middleBlock,
595 RenderObject* beforeChild, RenderBoxModelObject* oldCont)
597 // Create a clone of this inline.
598 RenderBlock* cloneBlock = clone();
599 if (!isAnonymousBlock())
600 cloneBlock->setContinuation(oldCont);
602 if (!beforeChild && isAfterContent(lastChild()))
603 beforeChild = lastChild();
605 // If we are moving inline children from |this| to cloneBlock, then we need
606 // to clear our line box tree.
607 if (beforeChild && childrenInline())
610 // Now take all of the children from beforeChild to the end and remove
611 // them from |this| and place them in the clone.
612 moveChildrenTo(cloneBlock, beforeChild, 0, true);
614 // Hook |clone| up as the continuation of the middle block.
615 if (!cloneBlock->isAnonymousBlock())
616 middleBlock->setContinuation(cloneBlock);
618 // We have been reparented and are now under the fromBlock. We need
619 // to walk up our block parent chain until we hit the containing anonymous columns block.
620 // Once we hit the anonymous columns block we're done.
621 RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
622 RenderBoxModelObject* currChild = this;
623 RenderObject* currChildNextSibling = currChild->nextSibling();
625 while (curr && curr != fromBlock) {
626 ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
628 RenderBlock* blockCurr = toRenderBlock(curr);
630 // Create a new clone.
631 RenderBlock* cloneChild = cloneBlock;
632 cloneBlock = blockCurr->clone();
634 // Insert our child clone as the first child.
635 cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
637 // Hook the clone up as a continuation of |curr|. Note we do encounter
638 // anonymous blocks possibly as we walk up the block chain. When we split an
639 // anonymous block, there's no need to do any continuation hookup, since we haven't
640 // actually split a real element.
641 if (!blockCurr->isAnonymousBlock()) {
642 oldCont = blockCurr->continuation();
643 blockCurr->setContinuation(cloneBlock);
644 cloneBlock->setContinuation(oldCont);
647 // Now we need to take all of the children starting from the first child
648 // *after* currChild and append them all to the clone.
649 blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
651 // Keep walking up the chain.
653 currChildNextSibling = currChild->nextSibling();
654 curr = toRenderBoxModelObject(curr->parent());
657 // Now we are at the columns block level. We need to put the clone into the toBlock.
658 toBlock->children()->appendChildNode(toBlock, cloneBlock);
660 // Now take all the children after currChild and remove them from the fromBlock
661 // and put them in the toBlock.
662 fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
665 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
666 RenderObject* newChild, RenderBoxModelObject* oldCont)
668 RenderBlock* pre = 0;
669 RenderBlock* block = containingColumnsBlock();
671 // Delete our line boxes before we do the inline split into continuations.
672 block->deleteLineBoxTree();
674 bool madeNewBeforeBlock = false;
675 if (block->isAnonymousColumnsBlock()) {
676 // We can reuse this block and make it the preBlock of the next continuation.
678 pre->removePositionedObjects(0);
679 pre->removeFloatingObjects();
680 block = toRenderBlock(block->parent());
682 // No anonymous block available for use. Make one.
683 pre = block->createAnonymousColumnsBlock();
684 pre->setChildrenInline(false);
685 madeNewBeforeBlock = true;
688 RenderBlock* post = block->createAnonymousColumnsBlock();
689 post->setChildrenInline(false);
691 RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
692 if (madeNewBeforeBlock)
693 block->children()->insertChildNode(block, pre, boxFirst);
694 block->children()->insertChildNode(block, newBlockBox, boxFirst);
695 block->children()->insertChildNode(block, post, boxFirst);
696 block->setChildrenInline(false);
698 if (madeNewBeforeBlock)
699 block->moveChildrenTo(pre, boxFirst, 0, true);
701 splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
703 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
704 // time in makeChildrenNonInline by just setting this explicitly up front.
705 newBlockBox->setChildrenInline(false);
707 // We delayed adding the newChild until now so that the |newBlockBox| would be fully
708 // connected, thus allowing newChild access to a renderArena should it need
709 // to wrap itself in additional boxes (e.g., table construction).
710 newBlockBox->addChild(newChild);
712 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
713 // get deleted properly. Because objects moves from the pre block into the post block, we want to
714 // make new line boxes instead of leaving the old line boxes around.
715 pre->setNeedsLayoutAndPrefWidthsRecalc();
716 block->setNeedsLayoutAndPrefWidthsRecalc();
717 post->setNeedsLayoutAndPrefWidthsRecalc();
720 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
722 RenderBlock* pre = 0;
723 RenderBlock* post = 0;
724 RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|. Assign to a variable
725 // so that we don't have to patch all of the rest of the code later on.
727 // Delete the block's line boxes before we do the split.
728 block->deleteLineBoxTree();
730 if (beforeChild && beforeChild->parent() != this)
731 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
733 if (beforeChild != firstChild()) {
734 pre = block->createAnonymousColumnsBlock();
735 pre->setChildrenInline(block->childrenInline());
739 post = block->createAnonymousColumnsBlock();
740 post->setChildrenInline(block->childrenInline());
743 RenderObject* boxFirst = block->firstChild();
745 block->children()->insertChildNode(block, pre, boxFirst);
746 block->children()->insertChildNode(block, newBlockBox, boxFirst);
748 block->children()->insertChildNode(block, post, boxFirst);
749 block->setChildrenInline(false);
751 // The pre/post blocks always have layers, so we know to always do a full insert/remove (so we pass true as the last argument).
752 block->moveChildrenTo(pre, boxFirst, beforeChild, true);
753 block->moveChildrenTo(post, beforeChild, 0, true);
755 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
756 // time in makeChildrenNonInline by just setting this explicitly up front.
757 newBlockBox->setChildrenInline(false);
759 // We delayed adding the newChild until now so that the |newBlockBox| would be fully
760 // connected, thus allowing newChild access to a renderArena should it need
761 // to wrap itself in additional boxes (e.g., table construction).
762 newBlockBox->addChild(newChild);
764 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
765 // get deleted properly. Because objects moved from the pre block into the post block, we want to
766 // make new line boxes instead of leaving the old line boxes around.
768 pre->setNeedsLayoutAndPrefWidthsRecalc();
769 block->setNeedsLayoutAndPrefWidthsRecalc();
771 post->setNeedsLayoutAndPrefWidthsRecalc();
774 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
776 // FIXME: This function is the gateway for the addition of column-span support. It will
777 // be added to in three stages:
778 // (1) Immediate children of a multi-column block can span.
779 // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
780 // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
781 // cross the streams and have to cope with both types of continuations mixed together).
782 // This function currently supports (1) and (2).
783 RenderBlock* columnsBlockAncestor = 0;
784 if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
785 && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
786 columnsBlockAncestor = containingColumnsBlock(false);
787 if (columnsBlockAncestor) {
788 // Make sure that none of the parent ancestors have a continuation.
789 // If yes, we do not want split the block into continuations.
790 RenderObject* curr = this;
791 while (curr && curr != columnsBlockAncestor) {
792 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
793 columnsBlockAncestor = 0;
796 curr = curr->parent();
800 return columnsBlockAncestor;
803 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
805 if (beforeChild && beforeChild->parent() != this) {
806 RenderObject* beforeChildContainer = beforeChild->parent();
807 while (beforeChildContainer->parent() != this)
808 beforeChildContainer = beforeChildContainer->parent();
809 ASSERT(beforeChildContainer);
811 if (beforeChildContainer->isAnonymous()) {
812 // If the requested beforeChild is not one of our children, then this is because
813 // there is an anonymous container within this object that contains the beforeChild.
814 RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
815 if (beforeChildAnonymousContainer->isAnonymousBlock()
816 #if ENABLE(FULLSCREEN_API)
817 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
818 || beforeChildAnonymousContainer->isRenderFullScreen()
819 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
822 // Insert the child into the anonymous block box instead of here.
823 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
824 beforeChild->parent()->addChild(newChild, beforeChild);
826 addChild(newChild, beforeChild->parent());
830 ASSERT(beforeChildAnonymousContainer->isTable());
831 if (newChild->isTablePart()) {
832 // Insert into the anonymous table.
833 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
837 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
839 ASSERT(beforeChild->parent() == this);
840 if (beforeChild->parent() != this) {
841 // We should never reach here. If we do, we need to use the
842 // safe fallback to use the topmost beforeChild container.
843 beforeChild = beforeChildContainer;
846 // We will reach here when beforeChild is a run-in element.
847 // If run-in element precedes a block-level element, it becomes the
848 // the first inline child of that block level element. The insertion
849 // point will be before that block-level element.
850 ASSERT(beforeChild->isRunIn());
851 beforeChild = beforeChildContainer;
855 // Nothing goes before the intruded run-in.
856 if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
857 beforeChild = beforeChild->nextSibling();
859 // Check for a spanning element in columns.
860 if (gColumnFlowSplitEnabled) {
861 RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
862 if (columnsBlockAncestor) {
863 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
864 // We are placing a column-span element inside a block.
865 RenderBlock* newBox = createAnonymousColumnSpanBlock();
867 if (columnsBlockAncestor != this && !isRenderFlowThread()) {
868 // We are nested inside a multi-column element and are being split by the span. We have to break up
869 // our block into continuations.
870 RenderBoxModelObject* oldContinuation = continuation();
872 // When we split an anonymous block, there's no need to do any continuation hookup,
873 // since we haven't actually split a real element.
874 if (!isAnonymousBlock())
875 setContinuation(newBox);
877 splitFlow(beforeChild, newBox, newChild, oldContinuation);
881 // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
882 // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
883 // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
884 makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
889 bool madeBoxesNonInline = false;
891 // A block has to either have all of its children inline, or all of its children as blocks.
892 // So, if our children are currently inline and a block child has to be inserted, we move all our
893 // inline children into anonymous block boxes.
894 if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
895 // This is a block with inline content. Wrap the inline content in anonymous blocks.
896 makeChildrenNonInline(beforeChild);
897 madeBoxesNonInline = true;
899 if (beforeChild && beforeChild->parent() != this) {
900 beforeChild = beforeChild->parent();
901 ASSERT(beforeChild->isAnonymousBlock());
902 ASSERT(beforeChild->parent() == this);
904 } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
905 // If we're inserting an inline child but all of our children are blocks, then we have to make sure
906 // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
907 // a new one is created and inserted into our list of children in the appropriate position.
908 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
910 if (afterChild && afterChild->isAnonymousBlock()) {
911 afterChild->addChild(newChild);
915 if (newChild->isInline()) {
916 // No suitable existing anonymous box - create a new one.
917 RenderBlock* newBox = createAnonymousBlock();
918 RenderBox::addChild(newBox, beforeChild);
919 newBox->addChild(newChild);
924 RenderBox::addChild(newChild, beforeChild);
926 // Handle placement of run-ins.
927 placeRunInIfNeeded(newChild);
929 if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
930 toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
931 // this object may be dead here
934 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
936 if (continuation() && !isAnonymousBlock())
937 addChildToContinuation(newChild, beforeChild);
939 addChildIgnoringContinuation(newChild, beforeChild);
942 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
944 if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
945 addChildToAnonymousColumnBlocks(newChild, beforeChild);
947 addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
950 static void getInlineRun(RenderObject* start, RenderObject* boundary,
951 RenderObject*& inlineRunStart,
952 RenderObject*& inlineRunEnd)
954 // Beginning at |start| we find the largest contiguous run of inlines that
955 // we can. We denote the run with start and end points, |inlineRunStart|
956 // and |inlineRunEnd|. Note that these two values may be the same if
957 // we encounter only one inline.
959 // We skip any non-inlines we encounter as long as we haven't found any
962 // |boundary| indicates a non-inclusive boundary point. Regardless of whether |boundary|
963 // is inline or not, we will not include it in a run with inlines before it. It's as though we encountered
966 // Start by skipping as many non-inlines as we can.
967 RenderObject * curr = start;
970 while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
971 curr = curr->nextSibling();
973 inlineRunStart = inlineRunEnd = curr;
976 return; // No more inline children to be found.
978 sawInline = curr->isInline();
980 curr = curr->nextSibling();
981 while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
983 if (curr->isInline())
985 curr = curr->nextSibling();
987 } while (!sawInline);
990 void RenderBlock::deleteLineBoxTree()
992 if (containsFloats()) {
993 // Clear references to originating lines, since the lines are being deleted
994 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
995 FloatingObjectSetIterator end = floatingObjectSet.end();
996 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
997 ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
998 (*it)->m_originatingLine = 0;
1001 m_lineBoxes.deleteLineBoxTree(renderArena());
1003 if (AXObjectCache* cache = document()->existingAXObjectCache())
1004 cache->recomputeIsIgnored(this);
1007 RootInlineBox* RenderBlock::createRootInlineBox()
1009 return new (renderArena()) RootInlineBox(this);
1012 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
1014 RootInlineBox* rootBox = createRootInlineBox();
1015 m_lineBoxes.appendLineBox(rootBox);
1017 if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1018 if (AXObjectCache* cache = document()->existingAXObjectCache())
1019 cache->recomputeIsIgnored(this);
1025 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
1027 // makeChildrenNonInline takes a block whose children are *all* inline and it
1028 // makes sure that inline children are coalesced under anonymous
1029 // blocks. If |insertionPoint| is defined, then it represents the insertion point for
1030 // the new block child that is causing us to have to wrap all the inlines. This
1031 // means that we cannot coalesce inlines before |insertionPoint| with inlines following
1032 // |insertionPoint|, because the new child is going to be inserted in between the inlines,
1034 ASSERT(isInlineBlockOrInlineTable() || !isInline());
1035 ASSERT(!insertionPoint || insertionPoint->parent() == this);
1037 setChildrenInline(false);
1039 RenderObject *child = firstChild();
1043 deleteLineBoxTree();
1045 // Since we are going to have block children, we have to move
1046 // back the run-in to its original place.
1047 if (child->isRunIn()) {
1048 moveRunInToOriginalPosition(child);
1049 child = firstChild();
1053 RenderObject *inlineRunStart, *inlineRunEnd;
1054 getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1056 if (!inlineRunStart)
1059 child = inlineRunEnd->nextSibling();
1061 RenderBlock* block = createAnonymousBlock();
1062 children()->insertChildNode(this, block, inlineRunStart);
1063 moveChildrenTo(block, inlineRunStart, child);
1067 for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1068 ASSERT(!c->isInline());
1074 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1076 ASSERT(child->isAnonymousBlock());
1077 ASSERT(!child->childrenInline());
1079 if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1082 RenderObject* firstAnChild = child->m_children.firstChild();
1083 RenderObject* lastAnChild = child->m_children.lastChild();
1085 RenderObject* o = firstAnChild;
1088 o = o->nextSibling();
1090 firstAnChild->setPreviousSibling(child->previousSibling());
1091 lastAnChild->setNextSibling(child->nextSibling());
1092 if (child->previousSibling())
1093 child->previousSibling()->setNextSibling(firstAnChild);
1094 if (child->nextSibling())
1095 child->nextSibling()->setPreviousSibling(lastAnChild);
1097 if (child == m_children.firstChild())
1098 m_children.setFirstChild(firstAnChild);
1099 if (child == m_children.lastChild())
1100 m_children.setLastChild(lastAnChild);
1102 if (child == m_children.firstChild())
1103 m_children.setFirstChild(child->nextSibling());
1104 if (child == m_children.lastChild())
1105 m_children.setLastChild(child->previousSibling());
1107 if (child->previousSibling())
1108 child->previousSibling()->setNextSibling(child->nextSibling());
1109 if (child->nextSibling())
1110 child->nextSibling()->setPreviousSibling(child->previousSibling());
1113 child->children()->setFirstChild(0);
1116 // Remove all the information in the flow thread associated with the leftover anonymous block.
1117 child->removeFromRenderFlowThread();
1119 child->setParent(0);
1120 child->setPreviousSibling(0);
1121 child->setNextSibling(0);
1126 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1128 if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1131 if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1132 || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1135 // FIXME: This check isn't required when inline run-ins can't be split into continuations.
1136 if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
1139 if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1140 || (next && (next->isRubyRun() || next->isRubyBase())))
1146 // Make sure the types of the anonymous blocks match up.
1147 return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1148 && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1151 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
1153 parent->setNeedsLayoutAndPrefWidthsRecalc();
1154 parent->setChildrenInline(child->childrenInline());
1155 RenderObject* nextSibling = child->nextSibling();
1157 RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1158 CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1160 RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
1161 anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1162 // Delete the now-empty block's lines and nuke it.
1163 anonBlock->deleteLineBoxTree();
1164 if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
1165 toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
1166 anonBlock->destroy();
1169 void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1171 moveAllChildrenTo(toBlock, fullRemoveInsert);
1173 // When a portion of the render tree is being detached, anonymous blocks
1174 // will be combined as their children are deleted. In this process, the
1175 // anonymous block later in the tree is merged into the one preceeding it.
1176 // It can happen that the later block (this) contains floats that the
1177 // previous block (toBlock) did not contain, and thus are not in the
1178 // floating objects list for toBlock. This can result in toBlock containing
1179 // floats that are not in it's floating objects list, but are in the
1180 // floating objects lists of siblings and parents. This can cause problems
1181 // when the float itself is deleted, since the deletion code assumes that
1182 // if a float is not in it's containing block's floating objects list, it
1183 // isn't in any floating objects list. In order to preserve this condition
1184 // (removing it has serious performance implications), we need to copy the
1185 // floating objects from the old block (this) to the new block (toBlock).
1186 // The float's metrics will likely all be wrong, but since toBlock is
1187 // already marked for layout, this will get fixed before anything gets
1189 // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
1190 if (m_floatingObjects) {
1191 if (!toBlock->m_floatingObjects)
1192 toBlock->createFloatingObjects();
1194 const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1195 FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1197 for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1198 FloatingObject* floatingObject = *it;
1200 // Don't insert the object again if it's already in the list
1201 if (toBlock->containsFloat(floatingObject->renderer()))
1204 toBlock->m_floatingObjects->add(floatingObject->clone());
1209 void RenderBlock::removeChild(RenderObject* oldChild)
1211 // No need to waste time in merging or removing empty anonymous blocks.
1212 // We can just bail out if our document is getting destroyed.
1213 if (documentBeingDestroyed()) {
1214 RenderBox::removeChild(oldChild);
1218 // This protects against column split flows when anonymous blocks are getting merged.
1219 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1221 // If this child is a block, and if our previous and next siblings are
1222 // both anonymous blocks with inline content, then we can go ahead and
1223 // fold the inline content back together.
1224 RenderObject* prev = oldChild->previousSibling();
1225 RenderObject* next = oldChild->nextSibling();
1226 bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1227 if (canMergeAnonymousBlocks && prev && next) {
1228 prev->setNeedsLayoutAndPrefWidthsRecalc();
1229 RenderBlock* nextBlock = toRenderBlock(next);
1230 RenderBlock* prevBlock = toRenderBlock(prev);
1232 if (prev->childrenInline() != next->childrenInline()) {
1233 RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1234 RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1236 // Place the inline children block inside of the block children block instead of deleting it.
1237 // In order to reuse it, we have to reset it to just be a generic anonymous block. Make sure
1238 // to clear out inherited column properties by just making a new style, and to also clear the
1239 // column span flag if it is set.
1240 ASSERT(!inlineChildrenBlock->continuation());
1241 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1242 // Cache this value as it might get changed in setStyle() call.
1243 bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1244 inlineChildrenBlock->setStyle(newStyle);
1245 children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1247 // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1248 blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1249 inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1250 next->setNeedsLayoutAndPrefWidthsRecalc();
1252 // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1253 // of "this". we null out prev or next so that is not used later in the function.
1254 if (inlineChildrenBlock == prevBlock)
1259 // Take all the children out of the |next| block and put them in
1260 // the |prev| block.
1261 nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
1263 // Delete the now-empty block's lines and nuke it.
1264 nextBlock->deleteLineBoxTree();
1265 nextBlock->destroy();
1270 RenderBox::removeChild(oldChild);
1272 RenderObject* child = prev ? prev : next;
1273 if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1274 // The removal has knocked us down to containing only a single anonymous
1275 // box. We can go ahead and pull the content right back up into our
1277 collapseAnonymousBoxChild(this, child);
1278 } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1279 // It's possible that the removal has knocked us down to a single anonymous
1280 // block with pseudo-style element siblings (e.g. first-letter). If these
1281 // are floating, then we need to pull the content up also.
1282 RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1283 if ((anonBlock->previousSibling() || anonBlock->nextSibling())
1284 && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
1285 && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
1286 collapseAnonymousBoxChild(this, anonBlock);
1290 if (!firstChild()) {
1291 // If this was our last child be sure to clear out our line boxes.
1292 if (childrenInline())
1293 deleteLineBoxTree();
1295 // If we are an empty anonymous block in the continuation chain,
1296 // we need to remove ourself and fix the continuation chain.
1297 if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1298 RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1299 while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
1300 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1301 for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1302 if (curr->virtualContinuation() != this)
1305 // Found our previous continuation. We just need to point it to
1306 // |this|'s next continuation.
1307 RenderBoxModelObject* nextContinuation = continuation();
1308 if (curr->isRenderInline())
1309 toRenderInline(curr)->setContinuation(nextContinuation);
1310 else if (curr->isRenderBlock())
1311 toRenderBlock(curr)->setContinuation(nextContinuation);
1313 ASSERT_NOT_REACHED();
1323 bool RenderBlock::isSelfCollapsingBlock() const
1325 // We are not self-collapsing if we
1326 // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1328 // (c) have border/padding,
1329 // (d) have a min-height
1330 // (e) have specified that one of our margins can't collapse using a CSS extension
1331 if (logicalHeight() > 0
1332 || isTable() || borderAndPaddingLogicalHeight()
1333 || style()->logicalMinHeight().isPositive()
1334 || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1337 Length logicalHeightLength = style()->logicalHeight();
1338 bool hasAutoHeight = logicalHeightLength.isAuto();
1339 if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1340 hasAutoHeight = true;
1341 for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1342 if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1343 hasAutoHeight = false;
1347 // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1348 // on whether we have content that is all self-collapsing or not.
1349 if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1350 // If the block has inline children, see if we generated any line boxes. If we have any
1351 // line boxes, then we can't be self-collapsing, since we have content.
1352 if (childrenInline())
1353 return !firstLineBox();
1355 // Whether or not we collapse is dependent on whether all our normal flow children
1356 // are also self-collapsing.
1357 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1358 if (child->isFloatingOrOutOfFlowPositioned())
1360 if (!child->isSelfCollapsingBlock())
1368 void RenderBlock::startDelayUpdateScrollInfo()
1370 if (gDelayUpdateScrollInfo == 0) {
1371 ASSERT(!gDelayedUpdateScrollInfoSet);
1372 gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1374 ASSERT(gDelayedUpdateScrollInfoSet);
1375 ++gDelayUpdateScrollInfo;
1378 void RenderBlock::finishDelayUpdateScrollInfo()
1380 --gDelayUpdateScrollInfo;
1381 ASSERT(gDelayUpdateScrollInfo >= 0);
1382 if (gDelayUpdateScrollInfo == 0) {
1383 ASSERT(gDelayedUpdateScrollInfoSet);
1385 OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1386 gDelayedUpdateScrollInfoSet = 0;
1388 for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1389 RenderBlock* block = *it;
1390 if (block->hasOverflowClip()) {
1391 block->layer()->updateScrollInfoAfterLayout();
1392 block->clearLayoutOverflow();
1398 void RenderBlock::updateScrollInfoAfterLayout()
1400 if (hasOverflowClip()) {
1401 if (style()->isFlippedBlocksWritingMode()) {
1402 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1403 // Workaround for now. We cannot delay the scroll info for overflow
1404 // for items with opposite writing directions, as the contents needs
1405 // to overflow in that direction
1406 layer()->updateScrollInfoAfterLayout();
1410 if (gDelayUpdateScrollInfo)
1411 gDelayedUpdateScrollInfoSet->add(this);
1413 layer()->updateScrollInfoAfterLayout();
1417 void RenderBlock::layout()
1419 StackStats::LayoutCheckPoint layoutCheckPoint;
1420 OverflowEventDispatcher dispatcher(this);
1422 // Update our first letter info now.
1423 updateFirstLetter();
1425 // Table cells call layoutBlock directly, so don't add any logic here. Put code into
1429 // It's safe to check for control clip here, since controls can never be table cells.
1430 // If we have a lightweight clip, there can never be any overflow from children.
1431 if (hasControlClip() && m_overflow && !gDelayUpdateScrollInfo)
1432 clearLayoutOverflow();
1434 invalidateBackgroundObscurationStatus();
1437 #if ENABLE(CSS_SHAPES)
1438 void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
1440 // FIXME: A future optimization would do a deep comparison for equality.
1441 if (shapeInside == oldShapeInside)
1445 ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
1446 shapeInsideInfo->dirtyShapeSize();
1448 setShapeInsideInfo(nullptr);
1449 markShapeInsideDescendantsForLayout();
1453 void RenderBlock::markShapeInsideDescendantsForLayout()
1455 if (!everHadLayout())
1457 if (childrenInline()) {
1458 setNeedsLayout(true);
1461 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1462 if (!child->isRenderBlock())
1464 RenderBlock* childBlock = toRenderBlock(child);
1465 childBlock->markShapeInsideDescendantsForLayout();
1470 static inline bool shapeInfoRequiresRelayout(const RenderBlock* block)
1472 #if !ENABLE(CSS_SHAPES)
1475 ShapeInsideInfo* info = block->shapeInsideInfo();
1477 info->setNeedsLayout(info->shapeSizeDirty());
1479 info = block->layoutShapeInsideInfo();
1480 return info && info->needsLayout();
1484 bool RenderBlock::updateRegionsAndExclusionsBeforeChildLayout(RenderFlowThread* flowThread)
1486 #if ENABLE(CSS_SHAPES)
1487 if (!flowThread && !shapeInsideInfo())
1491 return shapeInfoRequiresRelayout(this);
1493 LayoutUnit oldHeight = logicalHeight();
1494 LayoutUnit oldTop = logicalTop();
1496 // Compute the maximum logical height content may cause this block to expand to
1497 // FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
1498 setLogicalHeight(LayoutUnit::max() / 2);
1499 updateLogicalHeight();
1501 #if ENABLE(CSS_SHAPES)
1505 // Set our start and end regions. No regions above or below us will be considered by our children. They are
1506 // effectively clamped to our region range.
1507 computeRegionRangeForBlock(flowThread);
1509 setLogicalHeight(oldHeight);
1510 setLogicalTop(oldTop);
1512 return shapeInfoRequiresRelayout(this);
1515 #if ENABLE(CSS_SHAPES)
1516 void RenderBlock::computeShapeSize()
1518 ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
1519 if (shapeInsideInfo) {
1520 bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
1521 shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
1526 void RenderBlock::updateRegionsAndExclusionsAfterChildLayout(RenderFlowThread* flowThread, bool heightChanged)
1528 #if ENABLE(CSS_SHAPES)
1529 // A previous sibling has changed dimension, so we need to relayout the shape with the content
1530 ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
1531 if (heightChanged && shapeInsideInfo)
1532 shapeInsideInfo->dirtyShapeSize();
1534 computeRegionRangeForBlock(flowThread);
1537 void RenderBlock::computeRegionRangeForBlock(RenderFlowThread* flowThread)
1540 flowThread->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
1543 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1545 LayoutUnit oldWidth = logicalWidth();
1546 LayoutUnit oldColumnWidth = desiredColumnWidth();
1548 updateLogicalWidth();
1551 bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1552 m_hasBorderOrPaddingLogicalWidthChanged = false;
1554 return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || hasBorderOrPaddingLogicalWidthChanged;
1557 void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
1559 ColumnInfo* colInfo = columnInfo();
1561 if (!pageLogicalHeight) {
1562 // We need to go ahead and set our explicit page height if one exists, so that we can
1563 // avoid doing two layout passes.
1564 updateLogicalHeight();
1565 LayoutUnit columnHeight = contentLogicalHeight();
1566 if (columnHeight > 0) {
1567 pageLogicalHeight = columnHeight;
1568 hasSpecifiedPageLogicalHeight = true;
1570 setLogicalHeight(0);
1573 if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout())
1574 pageLogicalHeightChanged = true;
1576 colInfo->setColumnHeight(pageLogicalHeight);
1578 if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1579 colInfo->clearForcedBreaks();
1581 colInfo->setPaginationUnit(paginationUnit());
1582 } else if (isRenderFlowThread()) {
1583 pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
1584 pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
1588 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
1590 ASSERT(needsLayout());
1592 if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1593 return; // cause us to come in here. Just bail.
1595 if (!relayoutChildren && simplifiedLayout())
1598 LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
1600 if (updateLogicalWidthAndColumnWidth())
1601 relayoutChildren = true;
1605 LayoutUnit previousHeight = logicalHeight();
1606 // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
1607 // for consistency with other render classes?
1608 setLogicalHeight(0);
1610 bool pageLogicalHeightChanged = false;
1611 bool hasSpecifiedPageLogicalHeight = false;
1612 checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
1614 RenderView* renderView = view();
1615 RenderStyle* styleToUse = style();
1616 LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
1618 // Regions changing widths can force us to relayout our children.
1619 RenderFlowThread* flowThread = flowThreadContainingBlock();
1620 if (logicalWidthChangedInRegions(flowThread))
1621 relayoutChildren = true;
1622 if (updateRegionsAndExclusionsBeforeChildLayout(flowThread))
1623 relayoutChildren = true;
1625 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1626 // our current maximal positive and negative margins. These values are used when we
1627 // are collapsed with adjacent blocks, so for example, if you have block A and B
1628 // collapsing together, then you'd take the maximal positive margin from both A and B
1629 // and subtract it from the maximal negative margin from both A and B to get the
1630 // true collapsed margin. This algorithm is recursive, so when we finish layout()
1631 // our block knows its current maximal positive/negative values.
1633 // Start out by setting our margin values to our current margins. Table cells have
1634 // no margins, so we don't fill in the values for table cells.
1635 bool isCell = isTableCell();
1637 initMaxMarginValues();
1639 setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
1640 setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
1641 setPaginationStrut(0);
1644 LayoutUnit repaintLogicalTop = 0;
1645 LayoutUnit repaintLogicalBottom = 0;
1646 LayoutUnit maxFloatLogicalBottom = 0;
1647 if (!firstChild() && !isAnonymousBlock())
1648 setChildrenInline(true);
1649 if (childrenInline())
1650 layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1652 layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1654 // Expand our intrinsic height to encompass floats.
1655 LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
1656 if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1657 setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1659 if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
1662 // Calculate our new height.
1663 LayoutUnit oldHeight = logicalHeight();
1664 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1666 // Before updating the final size of the flow thread make sure a forced break is applied after the content.
1667 // This ensures the size information is correctly computed for the last auto-height region receiving content.
1668 if (isRenderFlowThread())
1669 toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
1671 updateLogicalHeight();
1672 LayoutUnit newHeight = logicalHeight();
1673 if (oldHeight != newHeight) {
1674 if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1675 // One of our children's floats may have become an overhanging float for us. We need to look for it.
1676 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1677 if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
1678 RenderBlock* block = toRenderBlock(child);
1679 if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1680 addOverhangingFloats(block, false);
1686 bool heightChanged = (previousHeight != newHeight);
1688 relayoutChildren = true;
1690 layoutPositionedObjects(relayoutChildren || isRoot());
1692 updateRegionsAndExclusionsAfterChildLayout(flowThread, heightChanged);
1694 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1695 computeOverflow(oldClientAfterEdge);
1699 fitBorderToLinesIfNeeded();
1701 if (renderView->layoutState()->m_pageLogicalHeight)
1702 setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
1704 updateLayerTransform();
1706 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1707 // we overflow or not.
1708 updateScrollInfoAfterLayout();
1710 // FIXME: This repaint logic should be moved into a separate helper function!
1711 // Repaint with our new bounds if they are different from our old bounds.
1712 bool didFullRepaint = repainter.repaintAfterLayout();
1713 if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1714 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1715 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
1716 LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1717 LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1718 if (hasOverflowClip()) {
1719 // 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.
1720 // 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.
1721 // layoutInlineChildren should be patched to compute the entire repaint rect.
1722 repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1723 repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1726 LayoutRect repaintRect;
1727 if (isHorizontalWritingMode())
1728 repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1730 repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1732 // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1733 adjustRectForColumns(repaintRect);
1735 repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1737 if (hasOverflowClip()) {
1738 // Adjust repaint rect for scroll offset
1739 repaintRect.move(-scrolledContentOffset());
1741 // Don't allow this rect to spill out of our overflow box.
1742 repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1745 // Make sure the rect is still non-empty after intersecting for overflow above
1746 if (!repaintRect.isEmpty()) {
1747 repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1748 if (hasReflection())
1749 repaintRectangle(reflectedRect(repaintRect));
1753 setNeedsLayout(false);
1756 void RenderBlock::addOverflowFromChildren()
1758 if (!hasColumns()) {
1759 if (childrenInline())
1760 addOverflowFromInlineChildren();
1762 addOverflowFromBlockChildren();
1764 ColumnInfo* colInfo = columnInfo();
1765 if (columnCount(colInfo)) {
1766 LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1767 addLayoutOverflow(lastRect);
1768 if (!hasOverflowClip())
1769 addVisualOverflow(lastRect);
1774 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1778 // Add overflow from children.
1779 addOverflowFromChildren();
1781 if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1782 addOverflowFromFloats();
1784 // Add in the overflow from positioned objects.
1785 addOverflowFromPositionedObjects();
1787 if (hasOverflowClip()) {
1788 // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1789 // and bottom padding. Set the axis we don't care about to be 1, since we want this overflow to always
1790 // be considered reachable.
1791 LayoutRect clientRect(clientBoxRect());
1792 LayoutRect rectToApply;
1793 if (isHorizontalWritingMode())
1794 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1796 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1797 addLayoutOverflow(rectToApply);
1798 if (hasRenderOverflow())
1799 m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1802 // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
1803 LayoutUnit textIndent = textIndentOffset();
1804 if (textIndent < 0) {
1805 LayoutRect clientRect(clientBoxRect());
1806 LayoutRect rectToApply = LayoutRect(clientRect.x() + min<LayoutUnit>(0, textIndent), clientRect.y(), clientRect.width() - min<LayoutUnit>(0, textIndent), clientRect.height());
1807 addVisualOverflow(rectToApply);
1810 // Add visual overflow from box-shadow and border-image-outset.
1811 addVisualEffectOverflow();
1813 // Add visual overflow from theme.
1814 addVisualOverflowFromTheme();
1816 if (isRenderFlowThread())
1817 toRenderFlowThread(this)->computeOverflowStateForRegions(oldClientAfterEdge);
1820 void RenderBlock::clearLayoutOverflow()
1825 if (visualOverflowRect() == borderBoxRect()) {
1830 m_overflow->setLayoutOverflow(borderBoxRect());
1833 void RenderBlock::addOverflowFromBlockChildren()
1835 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1836 if (!child->isFloatingOrOutOfFlowPositioned())
1837 addOverflowFromChild(child);
1841 void RenderBlock::addOverflowFromFloats()
1843 if (!m_floatingObjects)
1846 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1847 FloatingObjectSetIterator end = floatingObjectSet.end();
1848 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1849 FloatingObject* r = *it;
1850 if (r->isDescendant())
1851 addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1855 void RenderBlock::addOverflowFromPositionedObjects()
1857 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1858 if (!positionedDescendants)
1861 RenderBox* positionedObject;
1862 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1863 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1864 positionedObject = *it;
1866 // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1867 if (positionedObject->style()->position() != FixedPosition) {
1868 LayoutUnit x = positionedObject->x();
1869 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1870 x -= verticalScrollbarWidth();
1871 addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
1876 void RenderBlock::addVisualOverflowFromTheme()
1878 if (!style()->hasAppearance())
1881 IntRect inflatedRect = pixelSnappedBorderBoxRect();
1882 theme()->adjustRepaintRect(this, inflatedRect);
1883 addVisualOverflow(inflatedRect);
1886 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1888 return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
1889 || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1892 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1894 bool isHorizontal = isHorizontalWritingMode();
1895 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1897 LayoutUnit logicalTop = logicalHeight();
1898 updateStaticInlinePositionForChild(child, logicalTop);
1900 if (!marginInfo.canCollapseWithMarginBefore()) {
1901 // Positioned blocks don't collapse margins, so add the margin provided by
1902 // the container now. The child's own margin is added later when calculating its logical top.
1903 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1904 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1905 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1908 RenderLayer* childLayer = child->layer();
1909 if (childLayer->staticBlockPosition() != logicalTop) {
1910 childLayer->setStaticBlockPosition(logicalTop);
1911 if (hasStaticBlockPosition)
1912 child->setChildNeedsLayout(true, MarkOnlyThis);
1916 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1918 // The float should be positioned taking into account the bottom margin
1919 // of the previous flow. We add that margin into the height, get the
1920 // float positioned properly, and then subtract the margin out of the
1921 // height again. In the case of self-collapsing blocks, we always just
1922 // use the top margins, since the self-collapsing block collapsed its
1923 // own bottom margin into its top margin.
1925 // Note also that the previous flow may collapse its margin into the top of
1926 // our block. If this is the case, then we do not add the margin in to our
1927 // height when computing the position of the float. This condition can be tested
1928 // for by simply calling canCollapseWithMarginBefore. See
1929 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1930 // an example of this scenario.
1931 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1932 setLogicalHeight(logicalHeight() + marginOffset);
1933 positionNewFloats();
1934 setLogicalHeight(logicalHeight() - marginOffset);
1937 static void destroyRunIn(RenderBoxModelObject* runIn)
1939 ASSERT(runIn->isRunIn());
1940 ASSERT(!runIn->firstChild());
1942 // Delete our line box tree. This is needed as our children got moved
1943 // and our line box tree is no longer valid.
1944 if (runIn->isRenderBlock())
1945 toRenderBlock(runIn)->deleteLineBoxTree();
1946 else if (runIn->isRenderInline())
1947 toRenderInline(runIn)->deleteLineBoxTree();
1949 ASSERT_NOT_REACHED();
1954 void RenderBlock::placeRunInIfNeeded(RenderObject* newChild)
1956 if (newChild->isRunIn())
1957 moveRunInUnderSiblingBlockIfNeeded(newChild);
1958 else if (RenderObject* prevSibling = newChild->previousSibling()) {
1959 if (prevSibling->isRunIn())
1960 moveRunInUnderSiblingBlockIfNeeded(prevSibling);
1964 RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
1966 ASSERT(runIn->isRunIn());
1967 ASSERT(runIn->node());
1969 RenderBoxModelObject* newRunIn = 0;
1970 if (!runIn->isRenderBlock())
1971 newRunIn = new (renderArena()) RenderBlock(runIn->node());
1973 newRunIn = new (renderArena()) RenderInline(toElement(runIn->node()));
1975 runIn->node()->setRenderer(newRunIn);
1976 newRunIn->setStyle(runIn->style());
1978 runIn->moveAllChildrenTo(newRunIn, true);
1983 void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
1985 ASSERT(runIn->isRunIn());
1987 // See if we have inline children. If the children aren't inline,
1988 // then just treat the run-in as a normal block.
1989 if (!runIn->childrenInline())
1992 // FIXME: We don't handle non-block elements with run-in for now.
1993 if (!runIn->isRenderBlock())
1996 // FIXME: We don't support run-ins with or as part of a continuation
1997 // as it makes the back-and-forth placing complex.
1998 if (runIn->isElementContinuation() || runIn->virtualContinuation())
2001 // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
2002 // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
2003 if (!runIn->canBeReplacedWithInlineRunIn())
2006 RenderObject* curr = runIn->nextSibling();
2007 if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
2010 if (toRenderBlock(curr)->beingDestroyed())
2013 // Per CSS3, "A run-in cannot run in to a block that already starts with a
2014 // run-in or that itself is a run-in".
2015 if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
2018 if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
2021 RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2022 RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2023 destroyRunIn(oldRunIn);
2025 // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
2026 // since it handles correct placement of the children, especially where we cannot insert
2027 // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
2028 curr->addChild(newRunIn, curr->firstChild());
2030 // Make sure that |this| get a layout since its run-in child moved.
2031 curr->setNeedsLayoutAndPrefWidthsRecalc();
2034 bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
2036 ASSERT(runIn->isRunIn());
2038 // If we don't have a parent, we can't be moved into our sibling block.
2042 // An intruded run-in needs to be an inline.
2043 if (!runIn->isRenderInline())
2049 void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
2051 ASSERT(runIn->isRunIn());
2053 if (!runInIsPlacedIntoSiblingBlock(runIn))
2056 // FIXME: Run-in that are now placed in sibling block can break up into continuation
2057 // chains when new children are added to it. We cannot easily send them back to their
2058 // original place since that requires writing integration logic with RenderInline::addChild
2059 // and all other places that might cause continuations to be created (without blowing away
2060 // |this|). Disabling this feature for now to prevent crashes.
2061 if (runIn->isElementContinuation() || runIn->virtualContinuation())
2064 RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2065 RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2066 destroyRunIn(oldRunIn);
2068 // Add the run-in block as our previous sibling.
2069 parent()->addChild(newRunIn, this);
2071 // Make sure that the parent holding the new run-in gets layout.
2072 parent()->setNeedsLayoutAndPrefWidthsRecalc();
2075 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
2077 bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
2078 bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
2079 bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
2081 // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
2082 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
2084 // Get the four margin values for the child and cache them.
2085 const MarginValues childMargins = marginValuesForChild(child);
2087 // Get our max pos and neg top margins.
2088 LayoutUnit posTop = childMargins.positiveMarginBefore();
2089 LayoutUnit negTop = childMargins.negativeMarginBefore();
2091 // For self-collapsing blocks, collapse our bottom margins into our
2092 // top to get new posTop and negTop values.
2093 if (childIsSelfCollapsing) {
2094 posTop = max(posTop, childMargins.positiveMarginAfter());
2095 negTop = max(negTop, childMargins.negativeMarginAfter());
2098 // See if the top margin is quirky. We only care if this child has
2099 // margins that will collapse with us.
2100 bool topQuirk = hasMarginBeforeQuirk(child);
2102 if (marginInfo.canCollapseWithMarginBefore()) {
2103 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2104 // This child is collapsing with the top of the
2105 // block. If it has larger margin values, then we need to update
2106 // our own maximal values.
2107 if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
2108 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
2110 // The minute any of the margins involved isn't a quirk, don't
2111 // collapse it away, even if the margin is smaller (www.webreference.com
2112 // has an example of this, a <dt> with 0.8em author-specified inside
2113 // a <dl> inside a <td>.
2114 if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
2115 setHasMarginBeforeQuirk(false);
2116 marginInfo.setDeterminedMarginBeforeQuirk(true);
2119 if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
2120 // We have no top margin and our top child has a quirky margin.
2121 // We will pick up this quirky margin and pass it through.
2122 // This deals with the <td><div><p> case.
2123 // Don't do this for a block that split two inlines though. You do
2124 // still apply margins in this case.
2125 setHasMarginBeforeQuirk(true);
2127 // The before margin of the container will also discard all the margins it is collapsing with.
2128 setMustDiscardMarginBefore();
2131 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
2132 if (childDiscardMarginBefore) {
2133 marginInfo.setDiscardMargin(true);
2134 marginInfo.clearMargin();
2137 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
2138 marginInfo.setHasMarginBeforeQuirk(topQuirk);
2140 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
2141 LayoutUnit logicalTop = beforeCollapseLogicalTop;
2142 if (childIsSelfCollapsing) {
2143 // 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.
2144 // Also, the child's top position equals the logical height of the container.
2145 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2146 // This child has no height. We need to compute our
2147 // position before we collapse the child's margins together,
2148 // so that we can get an accurate position for the zero-height block.
2149 LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
2150 LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
2151 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
2153 // Now collapse the child's margins together, which means examining our
2154 // bottom margin values as well.
2155 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
2156 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
2158 if (!marginInfo.canCollapseWithMarginBefore())
2159 // We need to make sure that the position of the self-collapsing block
2160 // is correct, since it could have overflowing content
2161 // that needs to be positioned correctly (e.g., a block that
2162 // had a specified height of 0 but that actually had subcontent).
2163 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
2166 if (mustSeparateMarginBeforeForChild(child)) {
2167 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
2168 // If we are at the before side of the block and we collapse, ignore the computed margin
2169 // and just add the child margin to the container height. This will correctly position
2170 // the child inside the container.
2171 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
2172 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
2173 logicalTop = logicalHeight();
2174 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
2175 || (!marginInfo.canCollapseMarginBeforeWithChildren()
2176 && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
2177 // We're collapsing with a previous sibling's margins and not
2178 // with the top of the block.
2179 setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
2180 logicalTop = logicalHeight();
2183 marginInfo.setDiscardMargin(childDiscardMarginAfter);
2185 if (!marginInfo.discardMargin()) {
2186 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2187 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2189 marginInfo.clearMargin();
2191 if (marginInfo.margin())
2192 marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
2195 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
2196 // collapsed into the page edge.
2197 LayoutState* layoutState = view()->layoutState();
2198 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
2199 && hasNextPage(beforeCollapseLogicalTop)) {
2200 LayoutUnit oldLogicalTop = logicalTop;
2201 logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
2202 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
2205 // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
2206 // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
2207 // or clear it anyway, so don't worry about any floating children it may contain.
2208 LayoutUnit oldLogicalHeight = logicalHeight();
2209 setLogicalHeight(logicalTop);
2210 RenderObject* prev = child->previousSibling();
2211 if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
2212 RenderBlock* block = toRenderBlock(prev);
2213 if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop)
2214 addOverhangingFloats(block, false);
2216 setLogicalHeight(oldLogicalHeight);
2221 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
2223 LayoutUnit heightIncrease = getClearDelta(child, yPos);
2224 if (!heightIncrease)
2227 if (child->isSelfCollapsingBlock()) {
2228 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
2230 // For self-collapsing blocks that clear, they can still collapse their
2231 // margins with following siblings. Reset the current margins to represent
2232 // the self-collapsing block's margins only.
2233 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
2234 if (!childDiscardMargin) {
2235 MarginValues childMargins = marginValuesForChild(child);
2236 marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
2237 marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
2239 marginInfo.clearMargin();
2240 marginInfo.setDiscardMargin(childDiscardMargin);
2243 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
2244 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
2245 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
2246 // for a block with height - if none is found then don't allow the margins to collapse with the parent.
2247 bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
2248 for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
2249 if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
2250 wouldCollapseMarginsWithParent = false;
2252 if (wouldCollapseMarginsWithParent)
2253 marginInfo.setCanCollapseMarginAfterWithChildren(false);
2255 // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
2256 // Move the top of the child box to the bottom of the float ignoring the child's top margin.
2257 LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
2258 setLogicalHeight(child->logicalTop() - collapsedMargin);
2259 // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
2260 heightIncrease -= max(LayoutUnit(), collapsedMargin);
2262 // Increase our height by the amount we had to clear.
2263 setLogicalHeight(logicalHeight() + heightIncrease);
2265 if (marginInfo.canCollapseWithMarginBefore()) {
2266 // We can no longer collapse with the top of the block since a clear
2267 // occurred. The empty blocks collapse into the cleared block.
2268 // FIXME: This isn't quite correct. Need clarification for what to do
2269 // if the height the cleared block is offset by is smaller than the
2270 // margins involved.
2271 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
2272 marginInfo.setAtBeforeSideOfBlock(false);
2274 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
2275 setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
2278 LayoutUnit logicalTop = yPos + heightIncrease;
2279 // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
2280 // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
2281 if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
2282 toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
2287 void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
2289 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
2290 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
2291 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2292 if ((document()->inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
2295 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
2296 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2297 if (child->style()->marginBeforeCollapse() == MDISCARD) {
2298 positiveMarginBefore = 0;
2299 negativeMarginBefore = 0;
2300 discardMarginBefore = true;
2304 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
2305 positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
2306 negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
2308 if (!child->isRenderBlock())
2311 RenderBlock* childBlock = toRenderBlock(child);
2312 if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
2315 MarginInfo childMarginInfo(childBlock, childBlock->borderBefore() + childBlock->paddingBefore(), childBlock->borderAfter() + childBlock->paddingAfter());
2316 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
2319 RenderBox* grandchildBox = childBlock->firstChildBox();
2320 for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
2321 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
2325 // Give up if there is clearance on the box, since it probably won't collapse into us.
2326 if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
2329 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
2330 if (grandchildBox->needsLayout()) {
2331 grandchildBox->computeAndSetBlockDirectionMargins(this);
2332 if (grandchildBox->isRenderBlock()) {
2333 RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
2334 grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
2335 grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
2339 // Collapse the margin of the grandchild box with our own to produce an estimate.
2340 childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2343 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
2345 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
2346 // relayout if there are intruding floats.
2347 LayoutUnit logicalTopEstimate = logicalHeight();
2348 if (!marginInfo.canCollapseWithMarginBefore()) {
2349 LayoutUnit positiveMarginBefore = 0;
2350 LayoutUnit negativeMarginBefore = 0;
2351 bool discardMarginBefore = false;
2352 if (child->selfNeedsLayout()) {
2353 // Try to do a basic estimation of how the collapse is going to go.
2354 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2356 // Use the cached collapsed margin values from a previous layout. Most of the time they
2358 MarginValues marginValues = marginValuesForChild(child);
2359 positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
2360 negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
2361 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
2364 // Collapse the result with our current margins.
2365 if (!discardMarginBefore)
2366 logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
2369 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
2371 LayoutState* layoutState = view()->layoutState();
2372 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
2373 && hasNextPage(logicalHeight()))
2374 logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
2376 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
2378 estimateWithoutPagination = logicalTopEstimate;
2380 if (layoutState->isPaginated()) {
2381 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2382 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
2384 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2385 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
2387 if (!child->selfNeedsLayout() && child->isRenderBlock())
2388 logicalTopEstimate += toRenderBlock(child)->paginationStrut();
2391 return logicalTopEstimate;
2394 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
2396 LayoutUnit startPosition = startOffsetForContent(region);
2398 // Add in our start margin.
2399 LayoutUnit oldPosition = startPosition + childMarginStart;
2400 LayoutUnit newPosition = oldPosition;
2402 LayoutUnit blockOffset = logicalTopForChild(child);
2404 blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
2406 LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
2408 if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
2409 if (childMarginStart < 0)
2410 startOff += childMarginStart;
2411 newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
2412 } else if (startOff != startPosition)
2413 newPosition = startOff + childMarginStart;
2415 return newPosition - oldPosition;
2418 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
2420 LayoutUnit startPosition = borderStart() + paddingStart();
2421 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2422 startPosition -= verticalScrollbarWidth();
2423 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
2425 // Add in our start margin.
2426 LayoutUnit childMarginStart = marginStartForChild(child);
2427 LayoutUnit newPosition = startPosition + childMarginStart;
2429 // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats. They need
2430 // to shift over as necessary to dodge any floats that might get in the way.
2431 if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
2432 newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
2434 setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
2437 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
2439 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
2440 // 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.
2441 // Don't update the max margin values because we won't need them anyway.
2442 if (marginInfo.discardMargin()) {
2443 setMustDiscardMarginAfter();
2447 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
2448 // with our children.
2449 setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
2451 if (!marginInfo.hasMarginAfterQuirk())
2452 setHasMarginAfterQuirk(false);
2454 if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
2455 // We have no bottom margin and our last child has a quirky margin.
2456 // We will pick up this quirky margin and pass it through.
2457 // This deals with the <td><div><p> case.
2458 setHasMarginAfterQuirk(true);
2462 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
2464 marginInfo.setAtAfterSideOfBlock(true);
2466 // If we can't collapse with children then go ahead and add in the bottom margin.
2467 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
2468 && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
2469 setLogicalHeight(logicalHeight() + marginInfo.margin());
2471 // Now add in our bottom border/padding.
2472 setLogicalHeight(logicalHeight() + afterSide);
2474 // Negative margins can cause our height to shrink below our minimal height (border/padding).
2475 // If this happens, ensure that the computed height is increased to the minimal height.
2476 setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
2478 // Update our bottom collapsed margin info.
2479 setCollapsedBottomMargin(marginInfo);
2482 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
2484 if (isHorizontalWritingMode()) {
2485 if (applyDelta == ApplyLayoutDelta)
2486 view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
2487 child->setX(logicalLeft);
2489 if (applyDelta == ApplyLayoutDelta)
2490 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
2491 child->setY(logicalLeft);
2495 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
2497 if (isHorizontalWritingMode()) {
2498 if (applyDelta == ApplyLayoutDelta)
2499 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
2500 child->setY(logicalTop);
2502 if (applyDelta == ApplyLayoutDelta)
2503 view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
2504 child->setX(logicalTop);
2508 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
2510 // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2511 // an auto value. Add a method to determine this, so that we can avoid the relayout.
2512 if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()) || child->hasViewportPercentageLogicalHeight())
2513 child->setChildNeedsLayout(true, MarkOnlyThis);
2515 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2516 if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2517 child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2520 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
2522 if (gPercentHeightDescendantsMap) {
2523 if (TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this)) {
2524 TrackedRendererListHashSet::iterator end = descendants->end();
2525 for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2526 RenderBox* box = *it;
2527 while (box != this) {
2528 if (box->normalChildNeedsLayout())
2530 box->setChildNeedsLayout(true, MarkOnlyThis);
2531 box = box->containingBlock();
2540 LayoutUnit beforeEdge = borderBefore() + paddingBefore();
2541 LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
2543 setLogicalHeight(beforeEdge);
2545 // Lay out our hypothetical grid line as though it occurs at the top of the block.
2546 if (view()->layoutState()->lineGrid() == this)
2547 layoutLineGridBox();
2549 // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
2550 MarginInfo marginInfo(this, beforeEdge, afterEdge);
2552 // Fieldsets need to find their legend and position it inside the border of the object.
2553 // The legend then gets skipped during normal layout. The same is true for ruby text.
2554 // It doesn't get included in the normal layout process but is instead skipped.
2555 RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2557 LayoutUnit previousFloatLogicalBottom = 0;
2558 maxFloatLogicalBottom = 0;
2560 RenderBox* next = firstChildBox();
2563 RenderBox* child = next;
2564 next = child->nextSiblingBox();
2566 if (childToExclude == child)
2567 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2569 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
2571 if (child->isOutOfFlowPositioned()) {
2572 child->containingBlock()->insertPositionedObject(child);
2573 adjustPositionedBlock(child, marginInfo);
2576 if (child->isFloating()) {
2577 insertFloatingObject(child);
2578 adjustFloatingBlock(marginInfo);
2582 // Lay out the child.
2583 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2586 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2587 // determining the correct collapsed bottom margin information.
2588 handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2591 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2593 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2594 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2596 // The child is a normal flow object. Compute the margins we will use for collapsing now.
2597 child->computeAndSetBlockDirectionMargins(this);
2599 // Try to guess our correct logical top position. In most cases this guess will
2600 // be correct. Only if we're wrong (when we compute the real logical top position)
2601 // will we have to potentially relayout.
2602 LayoutUnit estimateWithoutPagination;
2603 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2605 // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2606 LayoutRect oldRect = child->frameRect();
2607 LayoutUnit oldLogicalTop = logicalTopForChild(child);
2609 #if !ASSERT_DISABLED
2610 LayoutSize oldLayoutDelta = view()->layoutDelta();
2612 // Go ahead and position the child as though it didn't collapse with the top.
2613 setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2615 RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2616 bool markDescendantsWithFloats = false;
2617 if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2618 markDescendantsWithFloats = true;
2619 #if ENABLE(SUBPIXEL_LAYOUT)
2620 else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
2621 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
2622 // very large elements. If it does the comparison with oldLogicalTop might yield a
2623 // false negative as adding and removing margins, borders etc from a saturated number
2624 // might yield incorrect results. If this is the case always mark for layout.
2625 markDescendantsWithFloats = true;
2627 else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2628 // If an element might be affected by the presence of floats, then always mark it for
2630 LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
2631 if (fb > logicalTopEstimate)
2632 markDescendantsWithFloats = true;
2635 if (childRenderBlock) {
2636 if (markDescendantsWithFloats)
2637 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2638 if (!child->isWritingModeRoot())
2639 previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
2642 if (!child->needsLayout())
2643 child->markForPaginationRelayoutIfNeeded();
2645 bool childHadLayout = child->everHadLayout();
2646 bool childNeededLayout = child->needsLayout();
2647 if (childNeededLayout)
2650 // Cache if we are at the top of the block right now.
2651 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2653 // Now determine the correct ypos based off examination of collapsing margin
2655 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2657 // Now check for clear.
2658 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2660 bool paginated = view()->layoutState()->isPaginated();
2662 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2663 atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2665 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2667 // Now we have a final top position. See if it really does end up being different from our estimate.
2668 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
2669 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
2670 if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
2671 if (child->shrinkToAvoidFloats()) {
2672 // The child's width depends on the line width.
2673 // When the child shifts to clear an item, its width can
2674 // change (because it has more available line width).
2675 // So go ahead and mark the item as dirty.
2676 child->setChildNeedsLayout(true, MarkOnlyThis);
2679 if (childRenderBlock) {
2680 if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2681 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2682 if (!child->needsLayout())
2683 child->markForPaginationRelayoutIfNeeded();
2686 // Our guess was wrong. Make the child lay itself out again.
2687 child->layoutIfNeeded();
2690 // We are no longer at the top of the block if we encounter a non-empty child.
2691 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2692 if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2693 marginInfo.setAtBeforeSideOfBlock(false);
2695 // Now place the child in the correct left position
2696 determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
2698 // Update our height now that the child has been placed in the correct position.
2699 setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2700 if (mustSeparateMarginAfterForChild(child)) {
2701 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2702 marginInfo.clearMargin();
2704 // If the child has overhanging floats that intrude into following siblings (or possibly out
2705 // of this block), then the parent gets notified of the floats now.
2706 if (childRenderBlock && childRenderBlock->containsFloats())
2707 maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2709 LayoutSize childOffset = child->location() - oldRect.location();
2710 if (childOffset.width() || childOffset.height()) {
2711 view()->addLayoutDelta(childOffset);
2713 // If the child moved, we have to repaint it as well as any floating/positioned
2714 // descendants. An exception is if we need a layout. In this case, we know we're going to
2715 // repaint ourselves (and the child) anyway.
2716 if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2717 child->repaintDuringLayoutIfMoved(oldRect);
2720 if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2722 child->repaintOverhangingFloats(true);
2726 // Check for an after page/column break.
2727 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2728 if (newHeight != height())
2729 setLogicalHeight(newHeight);
2732 ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
2735 void RenderBlock::simplifiedNormalFlowLayout()
2737 if (childrenInline()) {
2738 ListHashSet<RootInlineBox*> lineBoxes;
2739 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2740 RenderObject* o = walker.current();
2741 if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
2742 o->layoutIfNeeded();
2743 if (toRenderBox(o)->inlineBoxWrapper()) {
2744 RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2747 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2748 o->setNeedsLayout(false);
2751 // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2752 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
2753 for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2754 RootInlineBox* box = *it;
2755 box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2758 for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2759 if (!box->isOutOfFlowPositioned())
2760 box->layoutIfNeeded();
2765 bool RenderBlock::simplifiedLayout()
2767 if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2770 LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2772 if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2775 // Lay out positioned descendants or objects that just need to recompute overflow.
2776 if (needsSimplifiedNormalFlowLayout())
2777 simplifiedNormalFlowLayout();
2779 // Lay out our positioned objects if our positioned child bit is set.
2780 // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
2781 // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the
2782 // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
2783 // are statically positioned and thus need to move with their absolute ancestors.
2784 bool canContainFixedPosObjects = canContainFixedPositionObjects();
2785 if (posChildNeedsLayout() || canContainFixedPosObjects)
2786 layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
2788 // Recompute our overflow information.
2789 // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2790 // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2791 // For now just always recompute overflow. This is no worse performance-wise than the old code that called rightmostPosition and
2792 // lowestPosition on every relayout so it's not a regression.
2793 // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
2794 // simplifiedLayout, we cache the value in m_overflow.
2795 LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
2796 computeOverflow(oldClientAfterEdge, true);
2800 updateLayerTransform();
2802 updateScrollInfoAfterLayout();
2804 setNeedsLayout(false);
2808 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child)
2810 if (child->style()->position() != FixedPosition)
2813 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
2814 bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
2815 if (!hasStaticBlockPosition && !hasStaticInlinePosition)
2818 RenderObject* o = child->parent();
2819 while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
2821 if (o->style()->position() != AbsolutePosition)
2824 RenderBox* box = toRenderBox(child);
2825 if (hasStaticInlinePosition) {
2826 LogicalExtentComputedValues computedValues;
2827 box->computeLogicalWidthInRegion(computedValues);
2828 LayoutUnit newLeft = computedValues.m_position;
2829 if (newLeft != box->logicalLeft())
2830 child->setChildNeedsLayout(true, MarkOnlyThis);
2831 } else if (hasStaticBlockPosition) {
2832 LayoutUnit oldTop = box->logicalTop();
2833 box->updateLogicalHeight();
2834 if (box->logicalTop() != oldTop)
2835 child->setChildNeedsLayout(true, MarkOnlyThis);
2839 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
2841 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2842 if (!positionedDescendants)
2846 view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2849 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2850 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2853 // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
2854 // if this is a fixed position element, mark it for layout if it has an abspos ancestor and needs to move with that ancestor, i.e.
2855 // it has static position.
2856 markFixedPositionObjectForLayoutIfNeeded(r);
2857 if (fixedPositionObjectsOnly) {
2858 r->layoutIfNeeded();
2862 // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2863 // non-positioned block. Rather than trying to detect all of these movement cases, we just always lay out positioned
2864 // objects that are positioned implicitly like this. Such objects are rare, and so in typical DHTML menu usage (where everything is
2865 // positioned explicitly) this should not incur a performance penalty.
2866 if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2867 r->setChildNeedsLayout(true, MarkOnlyThis);
2869 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2870 if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2871 r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2873 if (!r->needsLayout())
2874 r->markForPaginationRelayoutIfNeeded();
2876 // We don't have to do a full layout. We just have to update our position. Try that first. If we have shrink-to-fit width
2877 // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2878 if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2879 r->setNeedsLayout(false);
2881 // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2882 // If it's wrong we'll lay out again.
2883 LayoutUnit oldLogicalTop = 0;
2884 bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2885 if (needsBlockDirectionLocationSetBeforeLayout) {
2886 if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2887 r->updateLogicalHeight();
2889 r->updateLogicalWidth();
2890 oldLogicalTop = logicalTopForChild(r);
2893 r->layoutIfNeeded();
2895 // Lay out again if our estimate was wrong.
2896 if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2897 r->setChildNeedsLayout(true, MarkOnlyThis);
2898 r->layoutIfNeeded();
2903 view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2906 void RenderBlock::markPositionedObjectsForLayout()
2908 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2909 if (positionedDescendants) {
2911 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2912 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2914 r->setChildNeedsLayout(true);
2919 void RenderBlock::markForPaginationRelayoutIfNeeded()
2921 ASSERT(!needsLayout());
2925 if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()) || shouldBreakAtLineToAvoidWidow())
2926 setChildNeedsLayout(true, MarkOnlyThis);
2929 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2931 // Repaint any overhanging floats (if we know we're the one to paint them).
2932 // Otherwise, bail out.
2933 if (!hasOverhangingFloats())
2936 // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2937 // in this block. Better yet would be to push extra state for the containers of other floats.
2938 LayoutStateDisabler layoutStateDisabler(view());
2939 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2940 FloatingObjectSetIterator end = floatingObjectSet.end();
2941 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2942 FloatingObject* r = *it;
2943 // Only repaint the object if it is overhanging, is not in its own layer, and
2944 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2945 // condition is replaced with being a descendant of us.
2946 if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
2947 r->m_renderer->repaint();
2948 r->m_renderer->repaintOverhangingFloats(false);
2953 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2955 LayoutPoint adjustedPaintOffset = paintOffset + location();
2957 PaintPhase phase = paintInfo.phase;
2959 // Check if we need to do anything at all.
2960 // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2961 // paints the root's background.
2963 LayoutRect overflowBox = overflowRectForPaintRejection();
2964 flipForWritingMode(overflowBox);
2965 overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2966 overflowBox.moveBy(adjustedPaintOffset);
2967 if (!overflowBox.intersects(paintInfo.rect))
2971 bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
2972 paintObject(paintInfo, adjustedPaintOffset);
2974 popContentsClip(paintInfo, phase, adjustedPaintOffset);
2976 // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
2977 // z-index. We paint after we painted the background/border, so that the scrollbars will
2978 // sit above the background/border.
2979 if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
2980 layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
2983 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2985 if (paintInfo.context->paintingDisabled())
2988 const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
2989 bool ruleTransparent = style()->columnRuleIsTransparent();
2990 EBorderStyle ruleStyle = style()->columnRuleStyle();
2991 LayoutUnit ruleThickness = style()->columnRuleWidth();
2992 LayoutUnit colGap = columnGap();
2993 bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent;
2997 ColumnInfo* colInfo = columnInfo();
2998 unsigned colCount = columnCount(colInfo);
3000 bool antialias = shouldAntialiasLines(paintInfo.context);
3002 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3003 bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
3004 LayoutUnit currLogicalLeftOffset = leftToRight ? LayoutUnit() : contentLogicalWidth();
3005 LayoutUnit ruleAdd = logicalLeftOffsetForContent();
3006 LayoutUnit ruleLogicalLeft = leftToRight ? LayoutUnit() : contentLogicalWidth();
3007 LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
3008 BoxSide boxSide = isHorizontalWritingMode()
3009 ? leftToRight ? BSLeft : BSRight
3010 : leftToRight ? BSTop : BSBottom;
3012 for (unsigned i = 0; i < colCount; i++) {
3013 // Move to the next position.
3015 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
3016 currLogicalLeftOffset += inlineDirectionSize + colGap;
3018 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
3019 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
3022 // Now paint the column rule.
3023 if (i < colCount - 1) {
3024 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
3025 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
3026 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
3027 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
3028 IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
3029 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3032 ruleLogicalLeft = currLogicalLeftOffset;
3035 bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
3036 LayoutUnit ruleLeft = isHorizontalWritingMode()
3037 ? borderLeft() + paddingLeft()
3038 : colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter());
3039 LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
3040 LayoutUnit ruleTop = isHorizontalWritingMode()
3041 ? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter())
3042 : borderStart() + paddingStart();
3043 LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
3044 LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
3047 if (isHorizontalWritingMode())
3048 ruleRect.setY(height() - ruleRect.maxY());
3050 ruleRect.setX(width() - ruleRect.maxX());
3053 ruleRect.moveBy(paintOffset);
3055 BoxSide boxSide = isHorizontalWritingMode()
3056 ? topToBottom ? BSTop : BSBottom
3057 : topToBottom ? BSLeft : BSRight;
3059 LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
3060 if (!isHorizontalWritingMode())
3061 step = step.transposedSize();
3063 for (unsigned i = 1; i < colCount; i++) {
3064 ruleRect.move(step);
3065 IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
3066 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3071 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
3073 // We need to do multiple passes, breaking up our child painting into strips.
3074 GraphicsContext* context = paintInfo.context;
3075 ColumnInfo* colInfo = columnInfo();
3076 unsigned colCount = columnCount(colInfo);
3079 LayoutUnit currLogicalTopOffset = 0;
3080 LayoutUnit colGap = columnGap();
3081 for (unsigned i = 0; i < colCount; i++) {
3082 // For each rect, we clip to the rect, and then we adjust our coords.
3083 LayoutRect colRect = columnRectAt(colInfo, i);
3084 flipForWritingMode(colRect);
3085 LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
3086 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3087 if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
3088 if (isHorizontalWritingMode())
3089 offset.expand(0, colRect.y() - borderTop() - paddingTop());
3091 offset.expand(colRect.x() - borderLeft() - paddingLeft(), 0);
3093 colRect.moveBy(paintOffset);
3094 PaintInfo info(paintInfo);
3095 info.rect.intersect(pixelSnappedIntRect(colRect));
3097 if (!info.rect.isEmpty()) {
3098 GraphicsContextStateSaver stateSaver(*context);
3099 LayoutRect clipRect(colRect);
3101 if (i < colCount - 1) {
3102 if (isHorizontalWritingMode())
3103 clipRect.expand(colGap / 2, 0);
3105 clipRect.expand(0, colGap / 2);
3107 // Each strip pushes a clip, since column boxes are specified as being
3108 // like overflow:hidden.
3109 // FIXME: Content and column rules that extend outside column boxes at the edges of the multi-column element
3110 // are clipped according to the 'overflow' property.
3111 context->clip(pixelSnappedIntRect(clipRect));
3113 // Adjust our x and y when painting.
3114 LayoutPoint adjustedPaintOffset = paintOffset + offset;
3116 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
3118 paintContents(info, adjustedPaintOffset);
3121 LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
3122 if (style()->isFlippedBlocksWritingMode())
3123 currLogicalTopOffset += blockDelta;
3125 currLogicalTopOffset -= blockDelta;
3129 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3131 // Avoid painting descendants of the root element when stylesheets haven't loaded. This eliminates FOUC.
3132 // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
3133 // will do a full repaint.
3134 if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
3137 if (childrenInline())
3138 m_lineBoxes.paint(this, paintInfo, paintOffset);
3140 PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
3141 newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
3143 // We don't paint our own background, but we do let the kids paint their backgrounds.
3144 PaintInfo paintInfoForChild(paintInfo);
3145 paintInfoForChild.phase = newPhase;
3146 paintInfoForChild.updateSubtreePaintRootForChildren(this);
3148 // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
3149 // NSViews. Do not add any more code for this.
3150 bool usePrintRect = !view()->printRect().isEmpty();
3151 paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
3155 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3157 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
3158 if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
3163 bool RenderBlock::paintChild(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3165 // Check for page-break-before: always, and if it's set, break and bail.
3166 bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
3167 LayoutUnit absoluteChildY = paintOffset.y() + child->y();
3168 if (checkBeforeAlways
3169 && absoluteChildY > paintInfo.rect.y()
3170 && absoluteChildY < paintInfo.rect.maxY()) {
3171 view()->setBestTruncatedAt(absoluteChildY, this, true);
3175 RenderView* renderView = view();
3176 if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
3177 // Paginate block-level replaced elements.
3178 if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
3179 if (absoluteChildY < renderView->truncatedAt())
3180 renderView->setBestTruncatedAt(absoluteChildY, child);
3181 // If we were able to truncate, don't paint.
3182 if (absoluteChildY >= renderView->truncatedAt())
3187 LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
3188 if (!child->hasSelfPaintingLayer() && !child->isFloating())
3189 child->paint(paintInfoForChild, childPoint);
3191 // Check for page-break-after: always, and if it's set, break and bail.
3192 bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
3193 if (checkAfterAlways
3194 && (absoluteChildY + child->height()) > paintInfo.rect.y()
3195 && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
3196 view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
3203 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
3205 // Paint the caret if the FrameSelection says so or if caret browsing is enabled
3206 bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
3207 RenderObject* caretPainter;
3208 bool isContentEditable;
3209 if (type == CursorCaret) {
3210 caretPainter = frame()->selection()->caretRenderer();
3211 isContentEditable = frame()->selection()->rendererIsEditable();
3213 caretPainter = frame()->page()->dragCaretController()->caretRenderer();
3214 isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
3217 if (caretPainter == this && (isContentEditable || caretBrowsing)) {
3218 if (type == CursorCaret)
3219 frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
3221 frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
3225 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3227 PaintPhase paintPhase = paintInfo.phase;
3229 // 1. paint background, borders etc
3230 if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
3231 if (hasBoxDecorations())