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 "HTMLInputElement.h"
38 #include "HTMLNames.h"
39 #include "HitTestLocation.h"
40 #include "HitTestResult.h"
41 #include "InlineIterator.h"
42 #include "InlineTextBox.h"
43 #include "LayoutRepainter.h"
44 #include "LogicalSelectionOffsetCaches.h"
45 #include "OverflowEvent.h"
47 #include "PaintInfo.h"
48 #include "RenderBoxRegionInfo.h"
49 #include "RenderCombineText.h"
50 #include "RenderDeprecatedFlexibleBox.h"
51 #include "RenderFlexibleBox.h"
52 #include "RenderInline.h"
53 #include "RenderLayer.h"
54 #include "RenderMarquee.h"
55 #include "RenderNamedFlowThread.h"
56 #include "RenderRegion.h"
57 #include "RenderTableCell.h"
58 #include "RenderTextFragment.h"
59 #include "RenderTheme.h"
60 #include "RenderView.h"
61 #include "SVGTextRunRenderingContext.h"
63 #include "ShadowRoot.h"
64 #include "TransformState.h"
65 #include <wtf/StackStats.h>
66 #include <wtf/TemporaryChange.h>
68 #if ENABLE(CSS_SHAPES)
69 #include "ShapeInsideInfo.h"
70 #include "ShapeOutsideInfo.h"
75 using namespace Unicode;
79 using namespace HTMLNames;
81 struct SameSizeAsRenderBlock : public RenderBox {
83 RenderObjectChildList children;
84 RenderLineBoxList lineBoxes;
88 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
90 struct SameSizeAsFloatingObject {
94 uint32_t bitfields : 8;
97 COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
99 struct SameSizeAsMarginInfo {
100 uint32_t bitfields : 16;
101 LayoutUnit margins[2];
104 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
105 static ColumnInfoMap* gColumnInfoMap = 0;
107 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
108 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
110 static TrackedContainerMap* gPositionedContainerMap = 0;
111 static TrackedContainerMap* gPercentHeightContainerMap = 0;
113 typedef WTF::HashMap<RenderBlock*, OwnPtr<ListHashSet<RenderInline*> > > ContinuationOutlineTableMap;
115 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
116 static int gDelayUpdateScrollInfo = 0;
117 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
119 static bool gColumnFlowSplitEnabled = true;
121 bool RenderBlock::s_canPropagateFloatIntoSibling = false;
123 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
124 // only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
125 class OverflowEventDispatcher {
126 WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
128 OverflowEventDispatcher(const RenderBlock* block)
130 , m_hadHorizontalLayoutOverflow(false)
131 , m_hadVerticalLayoutOverflow(false)
133 m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document()->hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
134 if (m_shouldDispatchEvent) {
135 m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
136 m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
140 ~OverflowEventDispatcher()
142 if (!m_shouldDispatchEvent)
145 bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
146 bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
148 bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
149 bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
150 if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
151 if (FrameView* frameView = m_block->document()->view())
152 frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
157 const RenderBlock* m_block;
158 bool m_shouldDispatchEvent;
159 bool m_hadHorizontalLayoutOverflow;
160 bool m_hadVerticalLayoutOverflow;
163 // Our MarginInfo state used when laying out block children.
164 RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
165 : m_atBeforeSideOfBlock(true)
166 , m_atAfterSideOfBlock(false)
167 , m_hasMarginBeforeQuirk(false)
168 , m_hasMarginAfterQuirk(false)
169 , m_determinedMarginBeforeQuirk(false)
170 , m_discardMargin(false)
172 RenderStyle* blockStyle = block->style();
173 ASSERT(block->isRenderView() || block->parent());
174 m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
175 && !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
176 && !block->isRenderFlowThread() && !block->isWritingModeRoot() && !block->parent()->isFlexibleBox()
177 && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth() && !blockStyle->columnSpan();
179 m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
181 // If any height other than auto is specified in CSS, then we don't collapse our bottom
182 // margins with our children's margins. To do otherwise would be to risk odd visual
183 // effects when the children overflow out of the parent block and yet still collapse
184 // with it. We also don't collapse if we have any bottom border/padding.
185 m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
186 (blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
188 m_quirkContainer = block->isTableCell() || block->isBody();
190 m_discardMargin = m_canCollapseMarginBeforeWithChildren && block->mustDiscardMarginBefore();
192 m_positiveMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxPositiveMarginBefore() : LayoutUnit();
193 m_negativeMargin = (m_canCollapseMarginBeforeWithChildren && !block->mustDiscardMarginBefore()) ? block->maxNegativeMarginBefore() : LayoutUnit();
196 // -------------------------------------------------------------------------------------------------------
198 RenderBlock::RenderBlock(ContainerNode* node)
201 , m_hasMarginBeforeQuirk(false)
202 , m_hasMarginAfterQuirk(false)
203 , m_beingDestroyed(false)
204 , m_hasMarkupTruncation(false)
205 , m_hasBorderOrPaddingLogicalWidthChanged(false)
207 setChildrenInline(true);
208 COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
209 COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
212 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
214 if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
215 TrackedRendererListHashSet::iterator end = descendantSet->end();
216 for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
217 TrackedContainerMap::iterator it = containerMap->find(*descendant);
218 ASSERT(it != containerMap->end());
219 if (it == containerMap->end())
221 HashSet<RenderBlock*>* containerSet = it->value.get();
222 ASSERT(containerSet->contains(block));
223 containerSet->remove(block);
224 if (containerSet->isEmpty())
225 containerMap->remove(it);
230 RenderBlock::~RenderBlock()
232 if (m_floatingObjects)
233 deleteAllValues(m_floatingObjects->set());
236 gColumnInfoMap->take(this);
238 if (gPercentHeightDescendantsMap)
239 removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
240 if (gPositionedDescendantsMap)
241 removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
244 RenderBlock* RenderBlock::createAnonymous(Document* document)
246 RenderBlock* renderer = new (document->renderArena()) RenderBlock(0);
247 renderer->setDocumentForAnonymous(document);
251 void RenderBlock::willBeDestroyed()
253 // Mark as being destroyed to avoid trouble with merges in removeChild().
254 m_beingDestroyed = true;
256 if (!documentBeingDestroyed()) {
257 if (firstChild() && firstChild()->isRunIn())
258 moveRunInToOriginalPosition(firstChild());
261 // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
262 // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
263 children()->destroyLeftoverChildren();
265 // Destroy our continuation before anything other than anonymous children.
266 // The reason we don't destroy it before anonymous children is that they may
267 // have continuations of their own that are anonymous children of our continuation.
268 RenderBoxModelObject* continuation = this->continuation();
270 continuation->destroy();
274 if (!documentBeingDestroyed()) {
275 if (firstLineBox()) {
276 // We can't wait for RenderBox::destroy to clear the selection,
277 // because by then we will have nuked the line boxes.
278 // FIXME: The FrameSelection should be responsible for this when it
279 // is notified of DOM mutations.
280 if (isSelectionBorder())
281 view()->clearSelection();
283 // If we are an anonymous block, then our line boxes might have children
284 // that will outlast this block. In the non-anonymous block case those
285 // children will be destroyed by the time we return from this function.
286 if (isAnonymousBlock()) {
287 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
288 while (InlineBox* childBox = box->firstChild())
293 parent()->dirtyLinesFromChangedChild(this);
296 m_lineBoxes.deleteLineBoxes(renderArena());
299 lineGridBox()->destroy(renderArena());
301 if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
302 gDelayedUpdateScrollInfoSet->remove(this);
304 RenderBox::willBeDestroyed();
307 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
309 RenderStyle* oldStyle = style();
310 s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
312 setReplaced(newStyle->isDisplayInlineType());
314 if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()) {
315 if (newStyle->position() == StaticPosition)
316 // Clear our positioned objects list. Our absolutely positioned descendants will be
317 // inserted into our containing block's positioned objects list during layout.
318 removePositionedObjects(0, NewContainingBlock);
319 else if (oldStyle->position() == StaticPosition) {
320 // Remove our absolutely positioned descendants from their current containing block.
321 // They will be inserted into our positioned objects list during layout.
322 RenderObject* cb = parent();
323 while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
324 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
325 cb = cb->containingBlock();
331 if (cb->isRenderBlock())
332 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
335 if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
336 markAllDescendantsWithFloatsForLayout();
339 RenderBox::styleWillChange(diff, newStyle);
342 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
344 if (newStyle->isHorizontalWritingMode())
345 return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
346 || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
347 || oldStyle->paddingLeft() != newStyle->paddingLeft()
348 || oldStyle->paddingRight() != newStyle->paddingRight();
350 return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
351 || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
352 || oldStyle->paddingTop() != newStyle->paddingTop()
353 || oldStyle->paddingBottom() != newStyle->paddingBottom();
356 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
358 RenderBox::styleDidChange(diff, oldStyle);
360 RenderStyle* newStyle = style();
362 #if ENABLE(CSS_SHAPES)
363 updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
366 if (!isAnonymousBlock()) {
367 // Ensure that all of our continuation blocks pick up the new style.
368 for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
369 RenderBoxModelObject* nextCont = currCont->continuation();
370 currCont->setContinuation(0);
371 currCont->setStyle(newStyle);
372 currCont->setContinuation(nextCont);
376 propagateStyleToAnonymousChildren(true);
379 // After our style changed, if we lose our ability to propagate floats into next sibling
380 // blocks, then we need to find the top most parent containing that overhanging float and
381 // then mark its descendants with floats for layout and clear all floats from its next
382 // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
383 bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
384 if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
385 RenderBlock* parentBlock = this;
386 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
387 FloatingObjectSetIterator end = floatingObjectSet.end();
389 for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
390 if (curr->isRenderBlock()) {
391 RenderBlock* currBlock = toRenderBlock(curr);
393 if (currBlock->hasOverhangingFloats()) {
394 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
395 RenderBox* renderer = (*it)->renderer();
396 if (currBlock->hasOverhangingFloat(renderer)) {
397 parentBlock = currBlock;
405 parentBlock->markAllDescendantsWithFloatsForLayout();
406 parentBlock->markSiblingsWithFloatsForLayout();
409 // It's possible for our border/padding to change, but for the overall logical width of the block to
410 // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
411 m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
414 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
416 if (beforeChild && beforeChild->parent() == this)
419 RenderBlock* curr = toRenderBlock(continuation());
420 RenderBlock* nextToLast = this;
421 RenderBlock* last = this;
423 if (beforeChild && beforeChild->parent() == curr) {
424 if (curr->firstChild() == beforeChild)
431 curr = toRenderBlock(curr->continuation());
434 if (!beforeChild && !last->firstChild())
439 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
441 RenderBlock* flow = continuationBefore(beforeChild);
442 ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
443 RenderBoxModelObject* beforeChildParent = 0;
445 beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
447 RenderBoxModelObject* cont = flow->continuation();
449 beforeChildParent = cont;
451 beforeChildParent = flow;
454 if (newChild->isFloatingOrOutOfFlowPositioned()) {
455 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
459 // A continuation always consists of two potential candidates: a block or an anonymous
460 // column span box holding column span children.
461 bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
462 bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
463 bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
465 if (flow == beforeChildParent) {
466 flow->addChildIgnoringContinuation(newChild, beforeChild);
470 // The goal here is to match up if we can, so that we can coalesce and create the
471 // minimal # of continuations needed for the inline.
472 if (childIsNormal == bcpIsNormal) {
473 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
476 if (flowIsNormal == childIsNormal) {
477 flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
480 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
484 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
486 ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
488 // The goal is to locate a suitable box in which to place our child.
489 RenderBlock* beforeChildParent = 0;
491 RenderObject* curr = beforeChild;
492 while (curr && curr->parent() != this)
493 curr = curr->parent();
494 beforeChildParent = toRenderBlock(curr);
495 ASSERT(beforeChildParent);
496 ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
498 beforeChildParent = toRenderBlock(lastChild());
500 // If the new child is floating or positioned it can just go in that block.
501 if (newChild->isFloatingOrOutOfFlowPositioned()) {
502 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
506 // See if the child can be placed in the box.
507 bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
508 bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
510 if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
511 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
516 // Create a new block of the correct type.
517 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
518 children()->appendChildNode(this, newBox);
519 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
523 RenderObject* immediateChild = beforeChild;
524 bool isPreviousBlockViable = true;
525 while (immediateChild->parent() != this) {
526 if (isPreviousBlockViable)
527 isPreviousBlockViable = !immediateChild->previousSibling();
528 immediateChild = immediateChild->parent();
530 if (isPreviousBlockViable && immediateChild->previousSibling()) {
531 toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
535 // Split our anonymous blocks.
536 RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
539 // Create a new anonymous box of the appropriate type.
540 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
541 children()->insertChildNode(this, newBox, newBeforeChild);
542 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
546 RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
548 RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
549 for (RenderObject* curr = this; curr; curr = curr->parent()) {
550 if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
551 || curr->isInlineBlockOrInlineTable())
554 // FIXME: Tables, RenderButtons, and RenderListItems all do special management
555 // of their children that breaks when the flow is split through them. Disabling
556 // multi-column for them to avoid this problem.
557 if (curr->isTable() || curr->isRenderButton() || curr->isListItem())
560 RenderBlock* currBlock = toRenderBlock(curr);
561 if (!currBlock->createsAnonymousWrapper())
562 firstChildIgnoringAnonymousWrappers = currBlock;
564 if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
565 return firstChildIgnoringAnonymousWrappers;
567 if (currBlock->isAnonymousColumnSpanBlock())
573 RenderBlock* RenderBlock::clone() const
575 RenderBlock* cloneBlock;
576 if (isAnonymousBlock()) {
577 cloneBlock = createAnonymousBlock();
578 cloneBlock->setChildrenInline(childrenInline());
581 RenderObject* cloneRenderer = toElement(node())->createRenderer(renderArena(), style());
582 cloneBlock = toRenderBlock(cloneRenderer);
583 cloneBlock->setStyle(style());
585 // This takes care of setting the right value of childrenInline in case
586 // generated content is added to cloneBlock and 'this' does not have
587 // generated content added yet.
588 cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
590 cloneBlock->setFlowThreadState(flowThreadState());
594 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
595 RenderBlock* middleBlock,
596 RenderObject* beforeChild, RenderBoxModelObject* oldCont)
598 // Create a clone of this inline.
599 RenderBlock* cloneBlock = clone();
600 if (!isAnonymousBlock())
601 cloneBlock->setContinuation(oldCont);
603 if (!beforeChild && isAfterContent(lastChild()))
604 beforeChild = lastChild();
606 // If we are moving inline children from |this| to cloneBlock, then we need
607 // to clear our line box tree.
608 if (beforeChild && childrenInline())
611 // Now take all of the children from beforeChild to the end and remove
612 // them from |this| and place them in the clone.
613 moveChildrenTo(cloneBlock, beforeChild, 0, true);
615 // Hook |clone| up as the continuation of the middle block.
616 if (!cloneBlock->isAnonymousBlock())
617 middleBlock->setContinuation(cloneBlock);
619 // We have been reparented and are now under the fromBlock. We need
620 // to walk up our block parent chain until we hit the containing anonymous columns block.
621 // Once we hit the anonymous columns block we're done.
622 RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
623 RenderBoxModelObject* currChild = this;
624 RenderObject* currChildNextSibling = currChild->nextSibling();
626 while (curr && curr != fromBlock) {
627 ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
629 RenderBlock* blockCurr = toRenderBlock(curr);
631 // Create a new clone.
632 RenderBlock* cloneChild = cloneBlock;
633 cloneBlock = blockCurr->clone();
635 // Insert our child clone as the first child.
636 cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
638 // Hook the clone up as a continuation of |curr|. Note we do encounter
639 // anonymous blocks possibly as we walk up the block chain. When we split an
640 // anonymous block, there's no need to do any continuation hookup, since we haven't
641 // actually split a real element.
642 if (!blockCurr->isAnonymousBlock()) {
643 oldCont = blockCurr->continuation();
644 blockCurr->setContinuation(cloneBlock);
645 cloneBlock->setContinuation(oldCont);
648 // Now we need to take all of the children starting from the first child
649 // *after* currChild and append them all to the clone.
650 blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
652 // Keep walking up the chain.
654 currChildNextSibling = currChild->nextSibling();
655 curr = toRenderBoxModelObject(curr->parent());
658 // Now we are at the columns block level. We need to put the clone into the toBlock.
659 toBlock->children()->appendChildNode(toBlock, cloneBlock);
661 // Now take all the children after currChild and remove them from the fromBlock
662 // and put them in the toBlock.
663 fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
666 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
667 RenderObject* newChild, RenderBoxModelObject* oldCont)
669 RenderBlock* pre = 0;
670 RenderBlock* block = containingColumnsBlock();
672 // Delete our line boxes before we do the inline split into continuations.
673 block->deleteLineBoxTree();
675 bool madeNewBeforeBlock = false;
676 if (block->isAnonymousColumnsBlock()) {
677 // We can reuse this block and make it the preBlock of the next continuation.
679 pre->removePositionedObjects(0);
680 pre->removeFloatingObjects();
681 block = toRenderBlock(block->parent());
683 // No anonymous block available for use. Make one.
684 pre = block->createAnonymousColumnsBlock();
685 pre->setChildrenInline(false);
686 madeNewBeforeBlock = true;
689 RenderBlock* post = block->createAnonymousColumnsBlock();
690 post->setChildrenInline(false);
692 RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
693 if (madeNewBeforeBlock)
694 block->children()->insertChildNode(block, pre, boxFirst);
695 block->children()->insertChildNode(block, newBlockBox, boxFirst);
696 block->children()->insertChildNode(block, post, boxFirst);
697 block->setChildrenInline(false);
699 if (madeNewBeforeBlock)
700 block->moveChildrenTo(pre, boxFirst, 0, true);
702 splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
704 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
705 // time in makeChildrenNonInline by just setting this explicitly up front.
706 newBlockBox->setChildrenInline(false);
708 // We delayed adding the newChild until now so that the |newBlockBox| would be fully
709 // connected, thus allowing newChild access to a renderArena should it need
710 // to wrap itself in additional boxes (e.g., table construction).
711 newBlockBox->addChild(newChild);
713 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
714 // get deleted properly. Because objects moves from the pre block into the post block, we want to
715 // make new line boxes instead of leaving the old line boxes around.
716 pre->setNeedsLayoutAndPrefWidthsRecalc();
717 block->setNeedsLayoutAndPrefWidthsRecalc();
718 post->setNeedsLayoutAndPrefWidthsRecalc();
721 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
723 RenderBlock* pre = 0;
724 RenderBlock* post = 0;
725 RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|. Assign to a variable
726 // so that we don't have to patch all of the rest of the code later on.
728 // Delete the block's line boxes before we do the split.
729 block->deleteLineBoxTree();
731 if (beforeChild && beforeChild->parent() != this)
732 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
734 if (beforeChild != firstChild()) {
735 pre = block->createAnonymousColumnsBlock();
736 pre->setChildrenInline(block->childrenInline());
740 post = block->createAnonymousColumnsBlock();
741 post->setChildrenInline(block->childrenInline());
744 RenderObject* boxFirst = block->firstChild();
746 block->children()->insertChildNode(block, pre, boxFirst);
747 block->children()->insertChildNode(block, newBlockBox, boxFirst);
749 block->children()->insertChildNode(block, post, boxFirst);
750 block->setChildrenInline(false);
752 // 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).
753 block->moveChildrenTo(pre, boxFirst, beforeChild, true);
754 block->moveChildrenTo(post, beforeChild, 0, true);
756 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
757 // time in makeChildrenNonInline by just setting this explicitly up front.
758 newBlockBox->setChildrenInline(false);
760 // We delayed adding the newChild until now so that the |newBlockBox| would be fully
761 // connected, thus allowing newChild access to a renderArena should it need
762 // to wrap itself in additional boxes (e.g., table construction).
763 newBlockBox->addChild(newChild);
765 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
766 // get deleted properly. Because objects moved from the pre block into the post block, we want to
767 // make new line boxes instead of leaving the old line boxes around.
769 pre->setNeedsLayoutAndPrefWidthsRecalc();
770 block->setNeedsLayoutAndPrefWidthsRecalc();
772 post->setNeedsLayoutAndPrefWidthsRecalc();
775 RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
777 // FIXME: This function is the gateway for the addition of column-span support. It will
778 // be added to in three stages:
779 // (1) Immediate children of a multi-column block can span.
780 // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
781 // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
782 // cross the streams and have to cope with both types of continuations mixed together).
783 // This function currently supports (1) and (2).
784 RenderBlock* columnsBlockAncestor = 0;
785 if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
786 && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
787 columnsBlockAncestor = containingColumnsBlock(false);
788 if (columnsBlockAncestor) {
789 // Make sure that none of the parent ancestors have a continuation.
790 // If yes, we do not want split the block into continuations.
791 RenderObject* curr = this;
792 while (curr && curr != columnsBlockAncestor) {
793 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
794 columnsBlockAncestor = 0;
797 curr = curr->parent();
801 return columnsBlockAncestor;
804 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
806 if (beforeChild && beforeChild->parent() != this) {
807 RenderObject* beforeChildContainer = beforeChild->parent();
808 while (beforeChildContainer->parent() != this)
809 beforeChildContainer = beforeChildContainer->parent();
810 ASSERT(beforeChildContainer);
812 if (beforeChildContainer->isAnonymous()) {
813 // If the requested beforeChild is not one of our children, then this is because
814 // there is an anonymous container within this object that contains the beforeChild.
815 RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
816 if (beforeChildAnonymousContainer->isAnonymousBlock()
817 #if ENABLE(FULLSCREEN_API)
818 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
819 || beforeChildAnonymousContainer->isRenderFullScreen()
820 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
823 // Insert the child into the anonymous block box instead of here.
824 if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
825 beforeChild->parent()->addChild(newChild, beforeChild);
827 addChild(newChild, beforeChild->parent());
831 ASSERT(beforeChildAnonymousContainer->isTable());
832 if (newChild->isTablePart()) {
833 // Insert into the anonymous table.
834 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
838 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
840 ASSERT(beforeChild->parent() == this);
841 if (beforeChild->parent() != this) {
842 // We should never reach here. If we do, we need to use the
843 // safe fallback to use the topmost beforeChild container.
844 beforeChild = beforeChildContainer;
847 // We will reach here when beforeChild is a run-in element.
848 // If run-in element precedes a block-level element, it becomes the
849 // the first inline child of that block level element. The insertion
850 // point will be before that block-level element.
851 ASSERT(beforeChild->isRunIn());
852 beforeChild = beforeChildContainer;
856 // Nothing goes before the intruded run-in.
857 if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
858 beforeChild = beforeChild->nextSibling();
860 // Check for a spanning element in columns.
861 if (gColumnFlowSplitEnabled) {
862 RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
863 if (columnsBlockAncestor) {
864 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
865 // We are placing a column-span element inside a block.
866 RenderBlock* newBox = createAnonymousColumnSpanBlock();
868 if (columnsBlockAncestor != this && !isRenderFlowThread()) {
869 // We are nested inside a multi-column element and are being split by the span. We have to break up
870 // our block into continuations.
871 RenderBoxModelObject* oldContinuation = continuation();
873 // When we split an anonymous block, there's no need to do any continuation hookup,
874 // since we haven't actually split a real element.
875 if (!isAnonymousBlock())
876 setContinuation(newBox);
878 splitFlow(beforeChild, newBox, newChild, oldContinuation);
882 // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
883 // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
884 // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
885 makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
890 bool madeBoxesNonInline = false;
892 // A block has to either have all of its children inline, or all of its children as blocks.
893 // So, if our children are currently inline and a block child has to be inserted, we move all our
894 // inline children into anonymous block boxes.
895 if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
896 // This is a block with inline content. Wrap the inline content in anonymous blocks.
897 makeChildrenNonInline(beforeChild);
898 madeBoxesNonInline = true;
900 if (beforeChild && beforeChild->parent() != this) {
901 beforeChild = beforeChild->parent();
902 ASSERT(beforeChild->isAnonymousBlock());
903 ASSERT(beforeChild->parent() == this);
905 } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
906 // If we're inserting an inline child but all of our children are blocks, then we have to make sure
907 // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
908 // a new one is created and inserted into our list of children in the appropriate position.
909 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
911 if (afterChild && afterChild->isAnonymousBlock()) {
912 afterChild->addChild(newChild);
916 if (newChild->isInline()) {
917 // No suitable existing anonymous box - create a new one.
918 RenderBlock* newBox = createAnonymousBlock();
919 RenderBox::addChild(newBox, beforeChild);
920 newBox->addChild(newChild);
925 RenderBox::addChild(newChild, beforeChild);
927 // Handle placement of run-ins.
928 placeRunInIfNeeded(newChild);
930 if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
931 toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
932 // this object may be dead here
935 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
937 if (continuation() && !isAnonymousBlock())
938 addChildToContinuation(newChild, beforeChild);
940 addChildIgnoringContinuation(newChild, beforeChild);
943 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
945 if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
946 addChildToAnonymousColumnBlocks(newChild, beforeChild);
948 addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
951 static void getInlineRun(RenderObject* start, RenderObject* boundary,
952 RenderObject*& inlineRunStart,
953 RenderObject*& inlineRunEnd)
955 // Beginning at |start| we find the largest contiguous run of inlines that
956 // we can. We denote the run with start and end points, |inlineRunStart|
957 // and |inlineRunEnd|. Note that these two values may be the same if
958 // we encounter only one inline.
960 // We skip any non-inlines we encounter as long as we haven't found any
963 // |boundary| indicates a non-inclusive boundary point. Regardless of whether |boundary|
964 // is inline or not, we will not include it in a run with inlines before it. It's as though we encountered
967 // Start by skipping as many non-inlines as we can.
968 RenderObject * curr = start;
971 while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
972 curr = curr->nextSibling();
974 inlineRunStart = inlineRunEnd = curr;
977 return; // No more inline children to be found.
979 sawInline = curr->isInline();
981 curr = curr->nextSibling();
982 while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
984 if (curr->isInline())
986 curr = curr->nextSibling();
988 } while (!sawInline);
991 void RenderBlock::deleteLineBoxTree()
993 if (containsFloats()) {
994 // Clear references to originating lines, since the lines are being deleted
995 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
996 FloatingObjectSetIterator end = floatingObjectSet.end();
997 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
998 ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
999 (*it)->m_originatingLine = 0;
1002 m_lineBoxes.deleteLineBoxTree(renderArena());
1004 if (AXObjectCache* cache = document()->existingAXObjectCache())
1005 cache->recomputeIsIgnored(this);
1008 RootInlineBox* RenderBlock::createRootInlineBox()
1010 return new (renderArena()) RootInlineBox(this);
1013 RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
1015 RootInlineBox* rootBox = createRootInlineBox();
1016 m_lineBoxes.appendLineBox(rootBox);
1018 if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && m_lineBoxes.firstLineBox() == rootBox) {
1019 if (AXObjectCache* cache = document()->existingAXObjectCache())
1020 cache->recomputeIsIgnored(this);
1026 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
1028 // makeChildrenNonInline takes a block whose children are *all* inline and it
1029 // makes sure that inline children are coalesced under anonymous
1030 // blocks. If |insertionPoint| is defined, then it represents the insertion point for
1031 // the new block child that is causing us to have to wrap all the inlines. This
1032 // means that we cannot coalesce inlines before |insertionPoint| with inlines following
1033 // |insertionPoint|, because the new child is going to be inserted in between the inlines,
1035 ASSERT(isInlineBlockOrInlineTable() || !isInline());
1036 ASSERT(!insertionPoint || insertionPoint->parent() == this);
1038 setChildrenInline(false);
1040 RenderObject *child = firstChild();
1044 deleteLineBoxTree();
1046 // Since we are going to have block children, we have to move
1047 // back the run-in to its original place.
1048 if (child->isRunIn()) {
1049 moveRunInToOriginalPosition(child);
1050 child = firstChild();
1054 RenderObject *inlineRunStart, *inlineRunEnd;
1055 getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1057 if (!inlineRunStart)
1060 child = inlineRunEnd->nextSibling();
1062 RenderBlock* block = createAnonymousBlock();
1063 children()->insertChildNode(this, block, inlineRunStart);
1064 moveChildrenTo(block, inlineRunStart, child);
1068 for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1069 ASSERT(!c->isInline());
1075 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1077 ASSERT(child->isAnonymousBlock());
1078 ASSERT(!child->childrenInline());
1080 if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1083 RenderObject* firstAnChild = child->m_children.firstChild();
1084 RenderObject* lastAnChild = child->m_children.lastChild();
1086 RenderObject* o = firstAnChild;
1089 o = o->nextSibling();
1091 firstAnChild->setPreviousSibling(child->previousSibling());
1092 lastAnChild->setNextSibling(child->nextSibling());
1093 if (child->previousSibling())
1094 child->previousSibling()->setNextSibling(firstAnChild);
1095 if (child->nextSibling())
1096 child->nextSibling()->setPreviousSibling(lastAnChild);
1098 if (child == m_children.firstChild())
1099 m_children.setFirstChild(firstAnChild);
1100 if (child == m_children.lastChild())
1101 m_children.setLastChild(lastAnChild);
1103 if (child == m_children.firstChild())
1104 m_children.setFirstChild(child->nextSibling());
1105 if (child == m_children.lastChild())
1106 m_children.setLastChild(child->previousSibling());
1108 if (child->previousSibling())
1109 child->previousSibling()->setNextSibling(child->nextSibling());
1110 if (child->nextSibling())
1111 child->nextSibling()->setPreviousSibling(child->previousSibling());
1114 child->children()->setFirstChild(0);
1117 // Remove all the information in the flow thread associated with the leftover anonymous block.
1118 child->removeFromRenderFlowThread();
1120 child->setParent(0);
1121 child->setPreviousSibling(0);
1122 child->setNextSibling(0);
1127 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1129 if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1132 if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1133 || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1136 // FIXME: This check isn't required when inline run-ins can't be split into continuations.
1137 if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
1140 if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1141 || (next && (next->isRubyRun() || next->isRubyBase())))
1147 // Make sure the types of the anonymous blocks match up.
1148 return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1149 && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1152 void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
1154 parent->setNeedsLayoutAndPrefWidthsRecalc();
1155 parent->setChildrenInline(child->childrenInline());
1156 RenderObject* nextSibling = child->nextSibling();
1158 RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1159 CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1161 RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
1162 anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1163 // Delete the now-empty block's lines and nuke it.
1164 anonBlock->deleteLineBoxTree();
1165 if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
1166 toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
1167 anonBlock->destroy();
1170 void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
1172 moveAllChildrenTo(toBlock, fullRemoveInsert);
1174 // When a portion of the render tree is being detached, anonymous blocks
1175 // will be combined as their children are deleted. In this process, the
1176 // anonymous block later in the tree is merged into the one preceeding it.
1177 // It can happen that the later block (this) contains floats that the
1178 // previous block (toBlock) did not contain, and thus are not in the
1179 // floating objects list for toBlock. This can result in toBlock containing
1180 // floats that are not in it's floating objects list, but are in the
1181 // floating objects lists of siblings and parents. This can cause problems
1182 // when the float itself is deleted, since the deletion code assumes that
1183 // if a float is not in it's containing block's floating objects list, it
1184 // isn't in any floating objects list. In order to preserve this condition
1185 // (removing it has serious performance implications), we need to copy the
1186 // floating objects from the old block (this) to the new block (toBlock).
1187 // The float's metrics will likely all be wrong, but since toBlock is
1188 // already marked for layout, this will get fixed before anything gets
1190 // See bug https://bugs.webkit.org/show_bug.cgi?id=115566
1191 if (m_floatingObjects) {
1192 if (!toBlock->m_floatingObjects)
1193 toBlock->createFloatingObjects();
1195 const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
1196 FloatingObjectSetIterator end = fromFloatingObjectSet.end();
1198 for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
1199 FloatingObject* floatingObject = *it;
1201 // Don't insert the object again if it's already in the list
1202 if (toBlock->containsFloat(floatingObject->renderer()))
1205 toBlock->m_floatingObjects->add(floatingObject->clone());
1210 void RenderBlock::removeChild(RenderObject* oldChild)
1212 // No need to waste time in merging or removing empty anonymous blocks.
1213 // We can just bail out if our document is getting destroyed.
1214 if (documentBeingDestroyed()) {
1215 RenderBox::removeChild(oldChild);
1219 // This protects against column split flows when anonymous blocks are getting merged.
1220 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1222 // If this child is a block, and if our previous and next siblings are
1223 // both anonymous blocks with inline content, then we can go ahead and
1224 // fold the inline content back together.
1225 RenderObject* prev = oldChild->previousSibling();
1226 RenderObject* next = oldChild->nextSibling();
1227 bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1228 if (canMergeAnonymousBlocks && prev && next) {
1229 prev->setNeedsLayoutAndPrefWidthsRecalc();
1230 RenderBlock* nextBlock = toRenderBlock(next);
1231 RenderBlock* prevBlock = toRenderBlock(prev);
1233 if (prev->childrenInline() != next->childrenInline()) {
1234 RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1235 RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1237 // Place the inline children block inside of the block children block instead of deleting it.
1238 // In order to reuse it, we have to reset it to just be a generic anonymous block. Make sure
1239 // to clear out inherited column properties by just making a new style, and to also clear the
1240 // column span flag if it is set.
1241 ASSERT(!inlineChildrenBlock->continuation());
1242 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1243 // Cache this value as it might get changed in setStyle() call.
1244 bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1245 inlineChildrenBlock->setStyle(newStyle);
1246 children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1248 // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1249 blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1250 inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1251 next->setNeedsLayoutAndPrefWidthsRecalc();
1253 // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1254 // of "this". we null out prev or next so that is not used later in the function.
1255 if (inlineChildrenBlock == prevBlock)
1260 // Take all the children out of the |next| block and put them in
1261 // the |prev| block.
1262 nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
1264 // Delete the now-empty block's lines and nuke it.
1265 nextBlock->deleteLineBoxTree();
1266 nextBlock->destroy();
1271 RenderBox::removeChild(oldChild);
1273 RenderObject* child = prev ? prev : next;
1274 if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1275 // The removal has knocked us down to containing only a single anonymous
1276 // box. We can go ahead and pull the content right back up into our
1278 collapseAnonymousBoxChild(this, child);
1279 } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1280 // It's possible that the removal has knocked us down to a single anonymous
1281 // block with pseudo-style element siblings (e.g. first-letter). If these
1282 // are floating, then we need to pull the content up also.
1283 RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1284 if ((anonBlock->previousSibling() || anonBlock->nextSibling())
1285 && (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
1286 && (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
1287 collapseAnonymousBoxChild(this, anonBlock);
1291 if (!firstChild()) {
1292 // If this was our last child be sure to clear out our line boxes.
1293 if (childrenInline())
1294 deleteLineBoxTree();
1296 // If we are an empty anonymous block in the continuation chain,
1297 // we need to remove ourself and fix the continuation chain.
1298 if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1299 RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1300 while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
1301 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1302 for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1303 if (curr->virtualContinuation() != this)
1306 // Found our previous continuation. We just need to point it to
1307 // |this|'s next continuation.
1308 RenderBoxModelObject* nextContinuation = continuation();
1309 if (curr->isRenderInline())
1310 toRenderInline(curr)->setContinuation(nextContinuation);
1311 else if (curr->isRenderBlock())
1312 toRenderBlock(curr)->setContinuation(nextContinuation);
1314 ASSERT_NOT_REACHED();
1324 bool RenderBlock::isSelfCollapsingBlock() const
1326 // We are not self-collapsing if we
1327 // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1329 // (c) have border/padding,
1330 // (d) have a min-height
1331 // (e) have specified that one of our margins can't collapse using a CSS extension
1332 if (logicalHeight() > 0
1333 || isTable() || borderAndPaddingLogicalHeight()
1334 || style()->logicalMinHeight().isPositive()
1335 || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1338 Length logicalHeightLength = style()->logicalHeight();
1339 bool hasAutoHeight = logicalHeightLength.isAuto();
1340 if (logicalHeightLength.isPercent() && !document()->inQuirksMode()) {
1341 hasAutoHeight = true;
1342 for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1343 if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1344 hasAutoHeight = false;
1348 // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1349 // on whether we have content that is all self-collapsing or not.
1350 if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1351 // If the block has inline children, see if we generated any line boxes. If we have any
1352 // line boxes, then we can't be self-collapsing, since we have content.
1353 if (childrenInline())
1354 return !firstLineBox();
1356 // Whether or not we collapse is dependent on whether all our normal flow children
1357 // are also self-collapsing.
1358 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1359 if (child->isFloatingOrOutOfFlowPositioned())
1361 if (!child->isSelfCollapsingBlock())
1369 void RenderBlock::startDelayUpdateScrollInfo()
1371 if (gDelayUpdateScrollInfo == 0) {
1372 ASSERT(!gDelayedUpdateScrollInfoSet);
1373 gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1375 ASSERT(gDelayedUpdateScrollInfoSet);
1376 ++gDelayUpdateScrollInfo;
1379 void RenderBlock::finishDelayUpdateScrollInfo()
1381 --gDelayUpdateScrollInfo;
1382 ASSERT(gDelayUpdateScrollInfo >= 0);
1383 if (gDelayUpdateScrollInfo == 0) {
1384 ASSERT(gDelayedUpdateScrollInfoSet);
1386 OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1387 gDelayedUpdateScrollInfoSet = 0;
1389 for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1390 RenderBlock* block = *it;
1391 if (block->hasOverflowClip()) {
1392 block->layer()->updateScrollInfoAfterLayout();
1393 block->clearLayoutOverflow();
1399 void RenderBlock::updateScrollInfoAfterLayout()
1401 if (hasOverflowClip()) {
1402 if (style()->isFlippedBlocksWritingMode()) {
1403 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1404 // Workaround for now. We cannot delay the scroll info for overflow
1405 // for items with opposite writing directions, as the contents needs
1406 // to overflow in that direction
1407 layer()->updateScrollInfoAfterLayout();
1411 if (gDelayUpdateScrollInfo)
1412 gDelayedUpdateScrollInfoSet->add(this);
1414 layer()->updateScrollInfoAfterLayout();
1418 void RenderBlock::layout()
1420 StackStats::LayoutCheckPoint layoutCheckPoint;
1421 OverflowEventDispatcher dispatcher(this);
1423 // Update our first letter info now.
1424 updateFirstLetter();
1426 // Table cells call layoutBlock directly, so don't add any logic here. Put code into
1430 // It's safe to check for control clip here, since controls can never be table cells.
1431 // If we have a lightweight clip, there can never be any overflow from children.
1432 if (hasControlClip() && m_overflow && !gDelayUpdateScrollInfo)
1433 clearLayoutOverflow();
1435 invalidateBackgroundObscurationStatus();
1438 #if ENABLE(CSS_SHAPES)
1439 void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
1441 // FIXME: A future optimization would do a deep comparison for equality.
1442 if (shapeInside == oldShapeInside)
1446 ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
1447 shapeInsideInfo->dirtyShapeSize();
1449 setShapeInsideInfo(nullptr);
1450 markShapeInsideDescendantsForLayout();
1454 void RenderBlock::markShapeInsideDescendantsForLayout()
1456 if (!everHadLayout())
1458 if (childrenInline()) {
1459 setNeedsLayout(true);
1462 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1463 if (!child->isRenderBlock())
1465 RenderBlock* childBlock = toRenderBlock(child);
1466 childBlock->markShapeInsideDescendantsForLayout();
1471 #if ENABLE(CSS_SHAPES)
1472 static inline bool shapeInfoRequiresRelayout(const RenderBlock* block)
1474 ShapeInsideInfo* info = block->shapeInsideInfo();
1476 info->setNeedsLayout(info->shapeSizeDirty());
1478 info = block->layoutShapeInsideInfo();
1479 return info && info->needsLayout();
1483 bool RenderBlock::updateShapesBeforeBlockLayout()
1485 #if ENABLE(CSS_SHAPES)
1486 if (!flowThreadContainingBlock() && !shapeInsideInfo())
1487 return shapeInfoRequiresRelayout(this);
1489 LayoutUnit oldHeight = logicalHeight();
1490 LayoutUnit oldTop = logicalTop();
1492 // Compute the maximum logical height content may cause this block to expand to
1493 // FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
1494 setLogicalHeight(RenderFlowThread::maxLogicalHeight());
1495 updateLogicalHeight();
1499 setLogicalHeight(oldHeight);
1500 setLogicalTop(oldTop);
1502 return shapeInfoRequiresRelayout(this);
1508 #if ENABLE(CSS_SHAPES)
1509 void RenderBlock::computeShapeSize()
1511 ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
1512 if (shapeInsideInfo) {
1513 bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
1514 shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
1519 void RenderBlock::updateShapesAfterBlockLayout(bool heightChanged)
1521 #if ENABLE(CSS_SHAPES)
1522 // A previous sibling has changed dimension, so we need to relayout the shape with the content
1523 ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
1524 if (heightChanged && shapeInsideInfo)
1525 shapeInsideInfo->dirtyShapeSize();
1529 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1531 LayoutUnit oldWidth = logicalWidth();
1532 LayoutUnit oldColumnWidth = desiredColumnWidth();
1534 updateLogicalWidth();
1537 bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1538 m_hasBorderOrPaddingLogicalWidthChanged = false;
1540 return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || hasBorderOrPaddingLogicalWidthChanged;
1543 void RenderBlock::checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight)
1545 ColumnInfo* colInfo = columnInfo();
1547 if (!pageLogicalHeight) {
1548 // We need to go ahead and set our explicit page height if one exists, so that we can
1549 // avoid doing two layout passes.
1550 updateLogicalHeight();
1551 LayoutUnit columnHeight = isRenderView() ? view()->pageOrViewLogicalHeight() : contentLogicalHeight();
1552 if (columnHeight > 0) {
1553 pageLogicalHeight = columnHeight;
1554 hasSpecifiedPageLogicalHeight = true;
1556 setLogicalHeight(0);
1559 if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout())
1560 pageLogicalHeightChanged = true;
1562 colInfo->setColumnHeight(pageLogicalHeight);
1564 if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
1565 colInfo->clearForcedBreaks();
1567 colInfo->setPaginationUnit(paginationUnit());
1568 } else if (isRenderFlowThread()) {
1569 pageLogicalHeight = 1; // This is just a hack to always make sure we have a page logical height.
1570 pageLogicalHeightChanged = toRenderFlowThread(this)->pageLogicalSizeChanged();
1574 bool RenderBlock::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
1576 if (!shouldBreakAtLineToAvoidWidow())
1580 setEverHadLayout(true);
1585 void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
1587 ASSERT(needsLayout());
1589 if (isInline() && !isInlineBlockOrInlineTable()) // Inline <form>s inside various table elements can
1590 return; // cause us to come in here. Just bail.
1592 if (!relayoutChildren && simplifiedLayout())
1595 LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
1597 if (updateLogicalWidthAndColumnWidth())
1598 relayoutChildren = true;
1602 LayoutUnit previousHeight = logicalHeight();
1603 // FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
1604 // for consistency with other render classes?
1605 setLogicalHeight(0);
1607 bool pageLogicalHeightChanged = false;
1608 bool hasSpecifiedPageLogicalHeight = false;
1609 checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
1611 RenderView* renderView = view();
1612 RenderStyle* styleToUse = style();
1613 LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
1615 // Regions changing widths can force us to relayout our children.
1616 RenderFlowThread* flowThread = flowThreadContainingBlock();
1617 if (logicalWidthChangedInRegions(flowThread))
1618 relayoutChildren = true;
1619 if (updateShapesBeforeBlockLayout())
1620 relayoutChildren = true;
1622 // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
1623 // our current maximal positive and negative margins. These values are used when we
1624 // are collapsed with adjacent blocks, so for example, if you have block A and B
1625 // collapsing together, then you'd take the maximal positive margin from both A and B
1626 // and subtract it from the maximal negative margin from both A and B to get the
1627 // true collapsed margin. This algorithm is recursive, so when we finish layout()
1628 // our block knows its current maximal positive/negative values.
1630 // Start out by setting our margin values to our current margins. Table cells have
1631 // no margins, so we don't fill in the values for table cells.
1632 bool isCell = isTableCell();
1634 initMaxMarginValues();
1636 setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
1637 setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
1638 setPaginationStrut(0);
1641 LayoutUnit repaintLogicalTop = 0;
1642 LayoutUnit repaintLogicalBottom = 0;
1643 LayoutUnit maxFloatLogicalBottom = 0;
1644 if (!firstChild() && !isAnonymousBlock())
1645 setChildrenInline(true);
1646 if (childrenInline())
1647 layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
1649 layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
1651 // Expand our intrinsic height to encompass floats.
1652 LayoutUnit toAdd = borderAndPaddingAfter() + scrollbarLogicalHeight();
1653 if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
1654 setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
1656 if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher) || relayoutToAvoidWidows(statePusher)) {
1657 ASSERT(!shouldBreakAtLineToAvoidWidow());
1661 // Calculate our new height.
1662 LayoutUnit oldHeight = logicalHeight();
1663 LayoutUnit oldClientAfterEdge = clientLogicalBottom();
1665 // Before updating the final size of the flow thread make sure a forced break is applied after the content.
1666 // This ensures the size information is correctly computed for the last auto-height region receiving content.
1667 if (isRenderFlowThread())
1668 toRenderFlowThread(this)->applyBreakAfterContent(oldClientAfterEdge);
1670 updateLogicalHeight();
1671 LayoutUnit newHeight = logicalHeight();
1672 if (oldHeight != newHeight) {
1673 if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
1674 // One of our children's floats may have become an overhanging float for us. We need to look for it.
1675 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
1676 if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
1677 RenderBlock* block = toRenderBlock(child);
1678 if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
1679 addOverhangingFloats(block, false);
1685 bool heightChanged = (previousHeight != newHeight);
1687 relayoutChildren = true;
1689 layoutPositionedObjects(relayoutChildren || isRoot());
1691 updateShapesAfterBlockLayout(heightChanged);
1693 // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
1694 computeOverflow(oldClientAfterEdge);
1698 fitBorderToLinesIfNeeded();
1700 if (renderView->layoutState()->m_pageLogicalHeight)
1701 setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
1703 updateLayerTransform();
1705 // Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
1706 // we overflow or not.
1707 updateScrollInfoAfterLayout();
1709 // FIXME: This repaint logic should be moved into a separate helper function!
1710 // Repaint with our new bounds if they are different from our old bounds.
1711 bool didFullRepaint = repainter.repaintAfterLayout();
1712 if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
1713 // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
1714 // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
1715 LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
1716 LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
1717 if (hasOverflowClip()) {
1718 // 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.
1719 // 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.
1720 // layoutInlineChildren should be patched to compute the entire repaint rect.
1721 repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
1722 repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
1725 LayoutRect repaintRect;
1726 if (isHorizontalWritingMode())
1727 repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
1729 repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
1731 // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
1732 adjustRectForColumns(repaintRect);
1734 repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
1736 if (hasOverflowClip()) {
1737 // Adjust repaint rect for scroll offset
1738 repaintRect.move(-scrolledContentOffset());
1740 // Don't allow this rect to spill out of our overflow box.
1741 repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
1744 // Make sure the rect is still non-empty after intersecting for overflow above
1745 if (!repaintRect.isEmpty()) {
1746 repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
1747 if (hasReflection())
1748 repaintRectangle(reflectedRect(repaintRect));
1752 setNeedsLayout(false);
1755 void RenderBlock::addOverflowFromChildren()
1757 if (!hasColumns()) {
1758 if (childrenInline())
1759 addOverflowFromInlineChildren();
1761 addOverflowFromBlockChildren();
1763 ColumnInfo* colInfo = columnInfo();
1764 if (columnCount(colInfo)) {
1765 LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1766 addLayoutOverflow(lastRect);
1767 if (!hasOverflowClip())
1768 addVisualOverflow(lastRect);
1773 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
1777 // Add overflow from children.
1778 addOverflowFromChildren();
1780 if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
1781 addOverflowFromFloats();
1783 // Add in the overflow from positioned objects.
1784 addOverflowFromPositionedObjects();
1786 if (hasOverflowClip()) {
1787 // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1788 // and bottom padding. Set the axis we don't care about to be 1, since we want this overflow to always
1789 // be considered reachable.
1790 LayoutRect clientRect(clientBoxRect());
1791 LayoutRect rectToApply;
1792 if (isHorizontalWritingMode())
1793 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1795 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1796 addLayoutOverflow(rectToApply);
1797 if (hasRenderOverflow())
1798 m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1801 // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
1802 LayoutUnit textIndent = textIndentOffset();
1803 if (textIndent < 0) {
1804 LayoutRect clientRect(clientBoxRect());
1805 LayoutRect rectToApply = LayoutRect(clientRect.x() + min<LayoutUnit>(0, textIndent), clientRect.y(), clientRect.width() - min<LayoutUnit>(0, textIndent), clientRect.height());
1806 addVisualOverflow(rectToApply);
1809 // Add visual overflow from box-shadow and border-image-outset.
1810 addVisualEffectOverflow();
1812 // Add visual overflow from theme.
1813 addVisualOverflowFromTheme();
1815 if (isRenderNamedFlowThread())
1816 toRenderNamedFlowThread(this)->computeOversetStateForRegions(oldClientAfterEdge);
1819 void RenderBlock::clearLayoutOverflow()
1824 if (visualOverflowRect() == borderBoxRect()) {
1829 m_overflow->setLayoutOverflow(borderBoxRect());
1832 void RenderBlock::addOverflowFromBlockChildren()
1834 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1835 if (!child->isFloatingOrOutOfFlowPositioned())
1836 addOverflowFromChild(child);
1840 void RenderBlock::addOverflowFromFloats()
1842 if (!m_floatingObjects)
1845 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1846 FloatingObjectSetIterator end = floatingObjectSet.end();
1847 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1848 FloatingObject* r = *it;
1849 if (r->isDescendant())
1850 addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
1854 void RenderBlock::addOverflowFromPositionedObjects()
1856 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1857 if (!positionedDescendants)
1860 RenderBox* positionedObject;
1861 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1862 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1863 positionedObject = *it;
1865 // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1866 if (positionedObject->style()->position() != FixedPosition) {
1867 LayoutUnit x = positionedObject->x();
1868 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
1869 x -= verticalScrollbarWidth();
1870 addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
1875 void RenderBlock::addVisualOverflowFromTheme()
1877 if (!style()->hasAppearance())
1880 IntRect inflatedRect = pixelSnappedBorderBoxRect();
1881 theme()->adjustRepaintRect(this, inflatedRect);
1882 addVisualOverflow(inflatedRect);
1885 bool RenderBlock::expandsToEncloseOverhangingFloats() const
1887 return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
1888 || hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
1891 void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
1893 bool isHorizontal = isHorizontalWritingMode();
1894 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
1896 LayoutUnit logicalTop = logicalHeight();
1897 updateStaticInlinePositionForChild(child, logicalTop);
1899 if (!marginInfo.canCollapseWithMarginBefore()) {
1900 // Positioned blocks don't collapse margins, so add the margin provided by
1901 // the container now. The child's own margin is added later when calculating its logical top.
1902 LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
1903 LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
1904 logicalTop += collapsedBeforePos - collapsedBeforeNeg;
1907 RenderLayer* childLayer = child->layer();
1908 if (childLayer->staticBlockPosition() != logicalTop) {
1909 childLayer->setStaticBlockPosition(logicalTop);
1910 if (hasStaticBlockPosition)
1911 child->setChildNeedsLayout(true, MarkOnlyThis);
1915 void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
1917 // The float should be positioned taking into account the bottom margin
1918 // of the previous flow. We add that margin into the height, get the
1919 // float positioned properly, and then subtract the margin out of the
1920 // height again. In the case of self-collapsing blocks, we always just
1921 // use the top margins, since the self-collapsing block collapsed its
1922 // own bottom margin into its top margin.
1924 // Note also that the previous flow may collapse its margin into the top of
1925 // our block. If this is the case, then we do not add the margin in to our
1926 // height when computing the position of the float. This condition can be tested
1927 // for by simply calling canCollapseWithMarginBefore. See
1928 // http://www.hixie.ch/tests/adhoc/css/box/block/margin-collapse/046.html for
1929 // an example of this scenario.
1930 LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? LayoutUnit() : marginInfo.margin();
1931 setLogicalHeight(logicalHeight() + marginOffset);
1932 positionNewFloats();
1933 setLogicalHeight(logicalHeight() - marginOffset);
1936 static void destroyRunIn(RenderBoxModelObject* runIn)
1938 ASSERT(runIn->isRunIn());
1939 ASSERT(!runIn->firstChild());
1941 // Delete our line box tree. This is needed as our children got moved
1942 // and our line box tree is no longer valid.
1943 if (runIn->isRenderBlock())
1944 toRenderBlock(runIn)->deleteLineBoxTree();
1945 else if (runIn->isRenderInline())
1946 toRenderInline(runIn)->deleteLineBoxTree();
1948 ASSERT_NOT_REACHED();
1953 void RenderBlock::placeRunInIfNeeded(RenderObject* newChild)
1955 if (newChild->isRunIn())
1956 moveRunInUnderSiblingBlockIfNeeded(newChild);
1957 else if (RenderObject* prevSibling = newChild->previousSibling()) {
1958 if (prevSibling->isRunIn())
1959 moveRunInUnderSiblingBlockIfNeeded(prevSibling);
1963 RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
1965 ASSERT(runIn->isRunIn());
1966 ASSERT(runIn->node());
1968 RenderBoxModelObject* newRunIn = 0;
1969 if (!runIn->isRenderBlock())
1970 newRunIn = new (renderArena()) RenderBlock(runIn->node());
1972 newRunIn = new (renderArena()) RenderInline(toElement(runIn->node()));
1974 runIn->node()->setRenderer(newRunIn);
1975 newRunIn->setStyle(runIn->style());
1977 runIn->moveAllChildrenTo(newRunIn, true);
1982 void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
1984 ASSERT(runIn->isRunIn());
1986 // See if we have inline children. If the children aren't inline,
1987 // then just treat the run-in as a normal block.
1988 if (!runIn->childrenInline())
1991 // FIXME: We don't handle non-block elements with run-in for now.
1992 if (!runIn->isRenderBlock())
1995 // FIXME: We don't support run-ins with or as part of a continuation
1996 // as it makes the back-and-forth placing complex.
1997 if (runIn->isElementContinuation() || runIn->virtualContinuation())
2000 // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
2001 // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
2002 if (!runIn->canBeReplacedWithInlineRunIn())
2005 RenderObject* curr = runIn->nextSibling();
2006 if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
2009 if (toRenderBlock(curr)->beingDestroyed())
2012 // Per CSS3, "A run-in cannot run in to a block that already starts with a
2013 // run-in or that itself is a run-in".
2014 if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
2017 if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
2020 RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2021 RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2022 destroyRunIn(oldRunIn);
2024 // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
2025 // since it handles correct placement of the children, especially where we cannot insert
2026 // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
2027 curr->addChild(newRunIn, curr->firstChild());
2029 // Make sure that |this| get a layout since its run-in child moved.
2030 curr->setNeedsLayoutAndPrefWidthsRecalc();
2033 bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
2035 ASSERT(runIn->isRunIn());
2037 // If we don't have a parent, we can't be moved into our sibling block.
2041 // An intruded run-in needs to be an inline.
2042 if (!runIn->isRenderInline())
2048 void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
2050 ASSERT(runIn->isRunIn());
2052 if (!runInIsPlacedIntoSiblingBlock(runIn))
2055 // FIXME: Run-in that are now placed in sibling block can break up into continuation
2056 // chains when new children are added to it. We cannot easily send them back to their
2057 // original place since that requires writing integration logic with RenderInline::addChild
2058 // and all other places that might cause continuations to be created (without blowing away
2059 // |this|). Disabling this feature for now to prevent crashes.
2060 if (runIn->isElementContinuation() || runIn->virtualContinuation())
2063 RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
2064 RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
2065 destroyRunIn(oldRunIn);
2067 // Add the run-in block as our previous sibling.
2068 parent()->addChild(newRunIn, this);
2070 // Make sure that the parent holding the new run-in gets layout.
2071 parent()->setNeedsLayoutAndPrefWidthsRecalc();
2074 LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
2076 bool childDiscardMarginBefore = mustDiscardMarginBeforeForChild(child);
2077 bool childDiscardMarginAfter = mustDiscardMarginAfterForChild(child);
2078 bool childIsSelfCollapsing = child->isSelfCollapsingBlock();
2080 // The child discards the before margin when the the after margin has discard in the case of a self collapsing block.
2081 childDiscardMarginBefore = childDiscardMarginBefore || (childDiscardMarginAfter && childIsSelfCollapsing);
2083 // Get the four margin values for the child and cache them.
2084 const MarginValues childMargins = marginValuesForChild(child);
2086 // Get our max pos and neg top margins.
2087 LayoutUnit posTop = childMargins.positiveMarginBefore();
2088 LayoutUnit negTop = childMargins.negativeMarginBefore();
2090 // For self-collapsing blocks, collapse our bottom margins into our
2091 // top to get new posTop and negTop values.
2092 if (childIsSelfCollapsing) {
2093 posTop = max(posTop, childMargins.positiveMarginAfter());
2094 negTop = max(negTop, childMargins.negativeMarginAfter());
2097 // See if the top margin is quirky. We only care if this child has
2098 // margins that will collapse with us.
2099 bool topQuirk = hasMarginBeforeQuirk(child);
2101 if (marginInfo.canCollapseWithMarginBefore()) {
2102 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2103 // This child is collapsing with the top of the
2104 // block. If it has larger margin values, then we need to update
2105 // our own maximal values.
2106 if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
2107 setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
2109 // The minute any of the margins involved isn't a quirk, don't
2110 // collapse it away, even if the margin is smaller (www.webreference.com
2111 // has an example of this, a <dt> with 0.8em author-specified inside
2112 // a <dl> inside a <td>.
2113 if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
2114 setHasMarginBeforeQuirk(false);
2115 marginInfo.setDeterminedMarginBeforeQuirk(true);
2118 if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
2119 // We have no top margin and our top child has a quirky margin.
2120 // We will pick up this quirky margin and pass it through.
2121 // This deals with the <td><div><p> case.
2122 // Don't do this for a block that split two inlines though. You do
2123 // still apply margins in this case.
2124 setHasMarginBeforeQuirk(true);
2126 // The before margin of the container will also discard all the margins it is collapsing with.
2127 setMustDiscardMarginBefore();
2130 // Once we find a child with discardMarginBefore all the margins collapsing with us must also discard.
2131 if (childDiscardMarginBefore) {
2132 marginInfo.setDiscardMargin(true);
2133 marginInfo.clearMargin();
2136 if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
2137 marginInfo.setHasMarginBeforeQuirk(topQuirk);
2139 LayoutUnit beforeCollapseLogicalTop = logicalHeight();
2140 LayoutUnit logicalTop = beforeCollapseLogicalTop;
2141 if (childIsSelfCollapsing) {
2142 // 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.
2143 // Also, the child's top position equals the logical height of the container.
2144 if (!childDiscardMarginBefore && !marginInfo.discardMargin()) {
2145 // This child has no height. We need to compute our
2146 // position before we collapse the child's margins together,
2147 // so that we can get an accurate position for the zero-height block.
2148 LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
2149 LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
2150 marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
2152 // Now collapse the child's margins together, which means examining our
2153 // bottom margin values as well.
2154 marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
2155 marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
2157 if (!marginInfo.canCollapseWithMarginBefore())
2158 // We need to make sure that the position of the self-collapsing block
2159 // is correct, since it could have overflowing content
2160 // that needs to be positioned correctly (e.g., a block that
2161 // had a specified height of 0 but that actually had subcontent).
2162 logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
2165 if (mustSeparateMarginBeforeForChild(child)) {
2166 ASSERT(!marginInfo.discardMargin() || (marginInfo.discardMargin() && !marginInfo.margin()));
2167 // If we are at the before side of the block and we collapse, ignore the computed margin
2168 // and just add the child margin to the container height. This will correctly position
2169 // the child inside the container.
2170 LayoutUnit separateMargin = !marginInfo.canCollapseWithMarginBefore() ? marginInfo.margin() : LayoutUnit(0);
2171 setLogicalHeight(logicalHeight() + separateMargin + marginBeforeForChild(child));
2172 logicalTop = logicalHeight();
2173 } else if (!marginInfo.discardMargin() && (!marginInfo.atBeforeSideOfBlock()
2174 || (!marginInfo.canCollapseMarginBeforeWithChildren()
2175 && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginBeforeQuirk())))) {
2176 // We're collapsing with a previous sibling's margins and not
2177 // with the top of the block.
2178 setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
2179 logicalTop = logicalHeight();
2182 marginInfo.setDiscardMargin(childDiscardMarginAfter);
2184 if (!marginInfo.discardMargin()) {
2185 marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
2186 marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
2188 marginInfo.clearMargin();
2190 if (marginInfo.margin())
2191 marginInfo.setHasMarginAfterQuirk(hasMarginAfterQuirk(child));
2194 // If margins would pull us past the top of the next page, then we need to pull back and pretend like the margins
2195 // collapsed into the page edge.
2196 LayoutState* layoutState = view()->layoutState();
2197 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
2198 && hasNextPage(beforeCollapseLogicalTop)) {
2199 LayoutUnit oldLogicalTop = logicalTop;
2200 logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
2201 setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
2204 // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
2205 // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
2206 // or clear it anyway, so don't worry about any floating children it may contain.
2207 LayoutUnit oldLogicalHeight = logicalHeight();
2208 setLogicalHeight(logicalTop);
2209 RenderObject* prev = child->previousSibling();
2210 if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
2211 RenderBlock* block = toRenderBlock(prev);
2212 if (block->containsFloats() && !block->avoidsFloats() && (block->logicalTop() + block->lowestFloatLogicalBottom()) > logicalTop)
2213 addOverhangingFloats(block, false);
2215 setLogicalHeight(oldLogicalHeight);
2220 LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
2222 LayoutUnit heightIncrease = getClearDelta(child, yPos);
2223 if (!heightIncrease)
2226 if (child->isSelfCollapsingBlock()) {
2227 bool childDiscardMargin = mustDiscardMarginBeforeForChild(child) || mustDiscardMarginAfterForChild(child);
2229 // For self-collapsing blocks that clear, they can still collapse their
2230 // margins with following siblings. Reset the current margins to represent
2231 // the self-collapsing block's margins only.
2232 // If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
2233 if (!childDiscardMargin) {
2234 MarginValues childMargins = marginValuesForChild(child);
2235 marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
2236 marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
2238 marginInfo.clearMargin();
2239 marginInfo.setDiscardMargin(childDiscardMargin);
2242 // "If the top and bottom margins of an element with clearance are adjoining, its margins collapse with
2243 // the adjoining margins of following siblings but that resulting margin does not collapse with the bottom margin of the parent block."
2244 // So the parent's bottom margin cannot collapse through this block or any subsequent self-collapsing blocks. Check subsequent siblings
2245 // for a block with height - if none is found then don't allow the margins to collapse with the parent.
2246 bool wouldCollapseMarginsWithParent = marginInfo.canCollapseMarginAfterWithChildren();
2247 for (RenderBox* curr = child->nextSiblingBox(); curr && wouldCollapseMarginsWithParent; curr = curr->nextSiblingBox()) {
2248 if (!curr->isFloatingOrOutOfFlowPositioned() && !curr->isSelfCollapsingBlock())
2249 wouldCollapseMarginsWithParent = false;
2251 if (wouldCollapseMarginsWithParent)
2252 marginInfo.setCanCollapseMarginAfterWithChildren(false);
2254 // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
2255 // Move the top of the child box to the bottom of the float ignoring the child's top margin.
2256 LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
2257 setLogicalHeight(child->logicalTop() - collapsedMargin);
2258 // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
2259 heightIncrease -= max(LayoutUnit(), collapsedMargin);
2261 // Increase our height by the amount we had to clear.
2262 setLogicalHeight(logicalHeight() + heightIncrease);
2264 if (marginInfo.canCollapseWithMarginBefore()) {
2265 // We can no longer collapse with the top of the block since a clear
2266 // occurred. The empty blocks collapse into the cleared block.
2267 // FIXME: This isn't quite correct. Need clarification for what to do
2268 // if the height the cleared block is offset by is smaller than the
2269 // margins involved.
2270 setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
2271 marginInfo.setAtBeforeSideOfBlock(false);
2273 // In case the child discarded the before margin of the block we need to reset the mustDiscardMarginBefore flag to the initial value.
2274 setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
2277 LayoutUnit logicalTop = yPos + heightIncrease;
2278 // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
2279 // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
2280 if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
2281 toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
2286 void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore, bool& discardMarginBefore) const
2288 // Give up if in quirks mode and we're a body/table cell and the top margin of the child box is quirky.
2289 // Give up if the child specified -webkit-margin-collapse: separate that prevents collapsing.
2290 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2291 if ((document()->inQuirksMode() && hasMarginAfterQuirk(child) && (isTableCell() || isBody())) || child->style()->marginBeforeCollapse() == MSEPARATE)
2294 // The margins are discarded by a child that specified -webkit-margin-collapse: discard.
2295 // FIXME: Use writing mode independent accessor for marginBeforeCollapse.
2296 if (child->style()->marginBeforeCollapse() == MDISCARD) {
2297 positiveMarginBefore = 0;
2298 negativeMarginBefore = 0;
2299 discardMarginBefore = true;
2303 LayoutUnit beforeChildMargin = marginBeforeForChild(child);
2304 positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
2305 negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
2307 if (!child->isRenderBlock())
2310 RenderBlock* childBlock = toRenderBlock(child);
2311 if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
2314 MarginInfo childMarginInfo(childBlock, childBlock->borderAndPaddingBefore(), childBlock->borderAndPaddingAfter());
2315 if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
2318 RenderBox* grandchildBox = childBlock->firstChildBox();
2319 for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
2320 if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
2324 // Give up if there is clearance on the box, since it probably won't collapse into us.
2325 if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
2328 // Make sure to update the block margins now for the grandchild box so that we're looking at current values.
2329 if (grandchildBox->needsLayout()) {
2330 grandchildBox->computeAndSetBlockDirectionMargins(this);
2331 if (grandchildBox->isRenderBlock()) {
2332 RenderBlock* grandchildBlock = toRenderBlock(grandchildBox);
2333 grandchildBlock->setHasMarginBeforeQuirk(grandchildBox->style()->hasMarginBeforeQuirk());
2334 grandchildBlock->setHasMarginAfterQuirk(grandchildBox->style()->hasMarginAfterQuirk());
2338 // Collapse the margin of the grandchild box with our own to produce an estimate.
2339 childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2342 LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
2344 // FIXME: We need to eliminate the estimation of vertical position, because when it's wrong we sometimes trigger a pathological
2345 // relayout if there are intruding floats.
2346 LayoutUnit logicalTopEstimate = logicalHeight();
2347 if (!marginInfo.canCollapseWithMarginBefore()) {
2348 LayoutUnit positiveMarginBefore = 0;
2349 LayoutUnit negativeMarginBefore = 0;
2350 bool discardMarginBefore = false;
2351 if (child->selfNeedsLayout()) {
2352 // Try to do a basic estimation of how the collapse is going to go.
2353 marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore, discardMarginBefore);
2355 // Use the cached collapsed margin values from a previous layout. Most of the time they
2357 MarginValues marginValues = marginValuesForChild(child);
2358 positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
2359 negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
2360 discardMarginBefore = mustDiscardMarginBeforeForChild(child);
2363 // Collapse the result with our current margins.
2364 if (!discardMarginBefore)
2365 logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
2368 // Adjust logicalTopEstimate down to the next page if the margins are so large that we don't fit on the current
2370 LayoutState* layoutState = view()->layoutState();
2371 if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
2372 && hasNextPage(logicalHeight()))
2373 logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
2375 logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
2377 estimateWithoutPagination = logicalTopEstimate;
2379 if (layoutState->isPaginated()) {
2380 // If the object has a page or column break value of "before", then we should shift to the top of the next page.
2381 logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
2383 // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
2384 logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
2386 if (!child->selfNeedsLayout() && child->isRenderBlock())
2387 logicalTopEstimate += toRenderBlock(child)->paginationStrut();
2390 return logicalTopEstimate;
2393 LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
2395 LayoutUnit startPosition = startOffsetForContent(region);
2397 // Add in our start margin.
2398 LayoutUnit oldPosition = startPosition + childMarginStart;
2399 LayoutUnit newPosition = oldPosition;
2401 LayoutUnit blockOffset = logicalTopForChild(child);
2403 blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
2405 LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
2407 if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
2408 if (childMarginStart < 0)
2409 startOff += childMarginStart;
2410 newPosition = max(newPosition, startOff); // Let the float sit in the child's margin if it can fit.
2411 } else if (startOff != startPosition)
2412 newPosition = startOff + childMarginStart;
2414 return newPosition - oldPosition;
2417 void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode applyDelta)
2419 LayoutUnit startPosition = borderStart() + paddingStart();
2420 if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
2421 startPosition -= verticalScrollbarWidth();
2422 LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
2424 // Add in our start margin.
2425 LayoutUnit childMarginStart = marginStartForChild(child);
2426 LayoutUnit newPosition = startPosition + childMarginStart;
2428 // Some objects (e.g., tables, horizontal rules, overflow:auto blocks) avoid floats. They need
2429 // to shift over as necessary to dodge any floats that might get in the way.
2430 if (child->avoidsFloats() && containsFloats() && !flowThreadContainingBlock())
2431 newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
2433 setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), applyDelta);
2436 void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
2438 if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
2439 // 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.
2440 // Don't update the max margin values because we won't need them anyway.
2441 if (marginInfo.discardMargin()) {
2442 setMustDiscardMarginAfter();
2446 // Update our max pos/neg bottom margins, since we collapsed our bottom margins
2447 // with our children.
2448 setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
2450 if (!marginInfo.hasMarginAfterQuirk())
2451 setHasMarginAfterQuirk(false);
2453 if (marginInfo.hasMarginAfterQuirk() && !marginAfter())
2454 // We have no bottom margin and our last child has a quirky margin.
2455 // We will pick up this quirky margin and pass it through.
2456 // This deals with the <td><div><p> case.
2457 setHasMarginAfterQuirk(true);
2461 void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
2463 marginInfo.setAtAfterSideOfBlock(true);
2465 // If we can't collapse with children then go ahead and add in the bottom margin.
2466 if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
2467 && (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
2468 setLogicalHeight(logicalHeight() + marginInfo.margin());
2470 // Now add in our bottom border/padding.
2471 setLogicalHeight(logicalHeight() + afterSide);
2473 // Negative margins can cause our height to shrink below our minimal height (border/padding).
2474 // If this happens, ensure that the computed height is increased to the minimal height.
2475 setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
2477 // Update our bottom collapsed margin info.
2478 setCollapsedBottomMargin(marginInfo);
2481 void RenderBlock::setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
2483 if (isHorizontalWritingMode()) {
2484 if (applyDelta == ApplyLayoutDelta)
2485 view()->addLayoutDelta(LayoutSize(child->x() - logicalLeft, 0));
2486 child->setX(logicalLeft);
2488 if (applyDelta == ApplyLayoutDelta)
2489 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalLeft));
2490 child->setY(logicalLeft);
2494 void RenderBlock::setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
2496 if (isHorizontalWritingMode()) {
2497 if (applyDelta == ApplyLayoutDelta)
2498 view()->addLayoutDelta(LayoutSize(0, child->y() - logicalTop));
2499 child->setY(logicalTop);
2501 if (applyDelta == ApplyLayoutDelta)
2502 view()->addLayoutDelta(LayoutSize(child->x() - logicalTop, 0));
2503 child->setX(logicalTop);
2507 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
2509 // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
2510 // an auto value. Add a method to determine this, so that we can avoid the relayout.
2511 if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()) || child->hasViewportPercentageLogicalHeight())
2512 child->setChildNeedsLayout(true, MarkOnlyThis);
2514 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2515 if (relayoutChildren && child->needsPreferredWidthsRecalculation())
2516 child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2519 void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants()
2521 if (!gPercentHeightDescendantsMap)
2524 TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
2528 TrackedRendererListHashSet::iterator end = descendants->end();
2529 for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2530 RenderBox* box = *it;
2531 while (box != this) {
2532 if (box->normalChildNeedsLayout())
2534 box->setChildNeedsLayout(true, MarkOnlyThis);
2536 // If the width of an image is affected by the height of a child (e.g., an image with an aspect ratio),
2537 // then we have to dirty preferred widths, since even enclosing blocks can become dirty as a result.
2538 // (A horizontal flexbox that contains an inline image wrapped in an anonymous block for example.)
2539 if (box->hasAspectRatio())
2540 box->setPreferredLogicalWidthsDirty(true);
2542 box = box->containingBlock();
2550 void RenderBlock::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
2552 dirtyForLayoutFromPercentageHeightDescendants();
2554 LayoutUnit beforeEdge = borderAndPaddingBefore();
2555 LayoutUnit afterEdge = borderAndPaddingAfter() + scrollbarLogicalHeight();
2557 setLogicalHeight(beforeEdge);
2559 // Lay out our hypothetical grid line as though it occurs at the top of the block.
2560 if (view()->layoutState()->lineGrid() == this)
2561 layoutLineGridBox();
2563 // The margin struct caches all our current margin collapsing state. The compact struct caches state when we encounter compacts,
2564 MarginInfo marginInfo(this, beforeEdge, afterEdge);
2566 // Fieldsets need to find their legend and position it inside the border of the object.
2567 // The legend then gets skipped during normal layout. The same is true for ruby text.
2568 // It doesn't get included in the normal layout process but is instead skipped.
2569 RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
2571 LayoutUnit previousFloatLogicalBottom = 0;
2572 maxFloatLogicalBottom = 0;
2574 RenderBox* next = firstChildBox();
2577 RenderBox* child = next;
2578 next = child->nextSiblingBox();
2580 if (childToExclude == child)
2581 continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
2583 updateBlockChildDirtyBitsBeforeLayout(relayoutChildren, child);
2585 if (child->isOutOfFlowPositioned()) {
2586 child->containingBlock()->insertPositionedObject(child);
2587 adjustPositionedBlock(child, marginInfo);
2590 if (child->isFloating()) {
2591 insertFloatingObject(child);
2592 adjustFloatingBlock(marginInfo);
2596 // Lay out the child.
2597 layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
2600 // Now do the handling of the bottom of the block, adding in our bottom border/padding and
2601 // determining the correct collapsed bottom margin information.
2602 handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
2605 void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
2607 LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
2608 LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
2610 // The child is a normal flow object. Compute the margins we will use for collapsing now.
2611 child->computeAndSetBlockDirectionMargins(this);
2613 // Try to guess our correct logical top position. In most cases this guess will
2614 // be correct. Only if we're wrong (when we compute the real logical top position)
2615 // will we have to potentially relayout.
2616 LayoutUnit estimateWithoutPagination;
2617 LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
2619 // Cache our old rect so that we can dirty the proper repaint rects if the child moves.
2620 LayoutRect oldRect = child->frameRect();
2621 LayoutUnit oldLogicalTop = logicalTopForChild(child);
2623 #if !ASSERT_DISABLED
2624 LayoutSize oldLayoutDelta = view()->layoutDelta();
2626 // Go ahead and position the child as though it didn't collapse with the top.
2627 setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
2628 estimateRegionRangeForBoxChild(child);
2630 RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
2631 bool markDescendantsWithFloats = false;
2632 if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
2633 markDescendantsWithFloats = true;
2634 #if ENABLE(SUBPIXEL_LAYOUT)
2635 else if (UNLIKELY(logicalTopEstimate.mightBeSaturated()))
2636 // logicalTopEstimate, returned by estimateLogicalTopPosition, might be saturated for
2637 // very large elements. If it does the comparison with oldLogicalTop might yield a
2638 // false negative as adding and removing margins, borders etc from a saturated number
2639 // might yield incorrect results. If this is the case always mark for layout.
2640 markDescendantsWithFloats = true;
2642 else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
2643 // If an element might be affected by the presence of floats, then always mark it for
2645 LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
2646 if (fb > logicalTopEstimate)
2647 markDescendantsWithFloats = true;
2650 if (childRenderBlock) {
2651 if (markDescendantsWithFloats)
2652 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2653 if (!child->isWritingModeRoot())
2654 previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
2657 if (!child->needsLayout())
2658 child->markForPaginationRelayoutIfNeeded();
2660 bool childHadLayout = child->everHadLayout();
2661 bool childNeededLayout = child->needsLayout();
2662 if (childNeededLayout)
2665 // Cache if we are at the top of the block right now.
2666 bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
2668 // Now determine the correct ypos based off examination of collapsing margin
2670 LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
2672 // Now check for clear.
2673 LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
2675 bool paginated = view()->layoutState()->isPaginated();
2677 logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
2678 atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
2680 setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
2682 // Now we have a final top position. See if it really does end up being different from our estimate.
2683 // clearFloatsIfNeeded can also mark the child as needing a layout even though we didn't move. This happens
2684 // when collapseMargins dynamically adds overhanging floats because of a child with negative margins.
2685 if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout() || (paginated && childRenderBlock && childRenderBlock->shouldBreakAtLineToAvoidWidow())) {
2686 if (child->shrinkToAvoidFloats()) {
2687 // The child's width depends on the line width.
2688 // When the child shifts to clear an item, its width can
2689 // change (because it has more available line width).
2690 // So go ahead and mark the item as dirty.
2691 child->setChildNeedsLayout(true, MarkOnlyThis);
2694 if (childRenderBlock) {
2695 if (!child->avoidsFloats() && childRenderBlock->containsFloats())
2696 childRenderBlock->markAllDescendantsWithFloatsForLayout();
2697 if (!child->needsLayout())
2698 child->markForPaginationRelayoutIfNeeded();
2701 // Our guess was wrong. Make the child lay itself out again.
2702 child->layoutIfNeeded();
2705 if (updateRegionRangeForBoxChild(child)) {
2706 child->setNeedsLayout(true, MarkOnlyThis);
2707 child->layoutIfNeeded();
2710 // We are no longer at the top of the block if we encounter a non-empty child.
2711 // This has to be done after checking for clear, so that margins can be reset if a clear occurred.
2712 if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
2713 marginInfo.setAtBeforeSideOfBlock(false);
2715 // Now place the child in the correct left position
2716 determineLogicalLeftPositionForChild(child, ApplyLayoutDelta);
2718 // Update our height now that the child has been placed in the correct position.
2719 setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
2720 if (mustSeparateMarginAfterForChild(child)) {
2721 setLogicalHeight(logicalHeight() + marginAfterForChild(child));
2722 marginInfo.clearMargin();
2724 // If the child has overhanging floats that intrude into following siblings (or possibly out
2725 // of this block), then the parent gets notified of the floats now.
2726 if (childRenderBlock && childRenderBlock->containsFloats())
2727 maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
2729 LayoutSize childOffset = child->location() - oldRect.location();
2730 if (childOffset.width() || childOffset.height()) {
2731 view()->addLayoutDelta(childOffset);
2733 // If the child moved, we have to repaint it as well as any floating/positioned
2734 // descendants. An exception is if we need a layout. In this case, we know we're going to
2735 // repaint ourselves (and the child) anyway.
2736 if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
2737 child->repaintDuringLayoutIfMoved(oldRect);
2740 if (!childHadLayout && child->checkForRepaintDuringLayout()) {
2742 child->repaintOverhangingFloats(true);
2746 // Check for an after page/column break.
2747 LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
2748 if (newHeight != height())
2749 setLogicalHeight(newHeight);
2752 ASSERT(view()->layoutDeltaMatches(oldLayoutDelta));
2755 void RenderBlock::simplifiedNormalFlowLayout()
2757 if (childrenInline()) {
2758 ListHashSet<RootInlineBox*> lineBoxes;
2759 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
2760 RenderObject* o = walker.current();
2761 if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
2762 o->layoutIfNeeded();
2763 if (toRenderBox(o)->inlineBoxWrapper()) {
2764 RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
2767 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
2768 o->setNeedsLayout(false);
2771 // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
2772 // FIXME: Find a way to invalidate the knownToHaveNoOverflow flag on the InlineBoxes.
2773 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
2774 for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
2775 RootInlineBox* box = *it;
2776 box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
2779 for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
2780 if (!box->isOutOfFlowPositioned())
2781 box->layoutIfNeeded();
2786 bool RenderBlock::simplifiedLayout()
2788 if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
2791 LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
2793 if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
2796 // Lay out positioned descendants or objects that just need to recompute overflow.
2797 if (needsSimplifiedNormalFlowLayout())
2798 simplifiedNormalFlowLayout();
2800 // Make sure a forced break is applied after the content if we are a flow thread in a simplified layout.
2801 // This ensures the size information is correctly computed for the last auto-height region receiving content.
2802 if (isRenderFlowThread())
2803 toRenderFlowThread(this)->applyBreakAfterContent(clientLogicalBottom());
2805 // Lay out our positioned objects if our positioned child bit is set.
2806 // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
2807 // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the
2808 // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
2809 // are statically positioned and thus need to move with their absolute ancestors.
2810 bool canContainFixedPosObjects = canContainFixedPositionObjects();
2811 if (posChildNeedsLayout() || canContainFixedPosObjects)
2812 layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
2814 // Recompute our overflow information.
2815 // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
2816 // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
2817 // For now just always recompute overflow. This is no worse performance-wise than the old code that called rightmostPosition and
2818 // lowestPosition on every relayout so it's not a regression.
2819 // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
2820 // simplifiedLayout, we cache the value in m_overflow.
2821 LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
2822 computeOverflow(oldClientAfterEdge, true);
2826 updateLayerTransform();
2828 updateScrollInfoAfterLayout();
2830 setNeedsLayout(false);
2834 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child)
2836 if (child->style()->position() != FixedPosition)
2839 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
2840 bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
2841 if (!hasStaticBlockPosition && !hasStaticInlinePosition)
2844 RenderObject* o = child->parent();
2845 while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
2847 if (o->style()->position() != AbsolutePosition)
2850 RenderBox* box = toRenderBox(child);
2851 if (hasStaticInlinePosition) {
2852 LogicalExtentComputedValues computedValues;
2853 box->computeLogicalWidthInRegion(computedValues);
2854 LayoutUnit newLeft = computedValues.m_position;
2855 if (newLeft != box->logicalLeft())
2856 child->setChildNeedsLayout(true, MarkOnlyThis);
2857 } else if (hasStaticBlockPosition) {
2858 LayoutUnit oldTop = box->logicalTop();
2859 box->updateLogicalHeight();
2860 if (box->logicalTop() != oldTop)
2861 child->setChildNeedsLayout(true, MarkOnlyThis);
2865 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
2867 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2868 if (!positionedDescendants)
2872 view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
2875 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2876 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2879 estimateRegionRangeForBoxChild(r);
2881 // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
2882 // 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.
2883 // it has static position.
2884 markFixedPositionObjectForLayoutIfNeeded(r);
2885 if (fixedPositionObjectsOnly) {
2886 r->layoutIfNeeded();
2890 // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
2891 // non-positioned block. Rather than trying to detect all of these movement cases, we just always lay out positioned
2892 // objects that are positioned implicitly like this. Such objects are rare, and so in typical DHTML menu usage (where everything is
2893 // positioned explicitly) this should not incur a performance penalty.
2894 if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
2895 r->setChildNeedsLayout(true, MarkOnlyThis);
2897 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
2898 if (relayoutChildren && r->needsPreferredWidthsRecalculation())
2899 r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
2901 if (!r->needsLayout())
2902 r->markForPaginationRelayoutIfNeeded();
2904 // 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
2905 // and we hit the available width constraint, the layoutIfNeeded() will catch it and do a full layout.
2906 if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
2907 r->setNeedsLayout(false);
2909 // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
2910 // If it's wrong we'll lay out again.
2911 LayoutUnit oldLogicalTop = 0;
2912 bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
2913 if (needsBlockDirectionLocationSetBeforeLayout) {
2914 if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
2915 r->updateLogicalHeight();
2917 r->updateLogicalWidth();
2918 oldLogicalTop = logicalTopForChild(r);
2921 r->layoutIfNeeded();
2923 // Lay out again if our estimate was wrong.
2924 if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
2925 r->setChildNeedsLayout(true, MarkOnlyThis);
2926 r->layoutIfNeeded();
2929 if (updateRegionRangeForBoxChild(r)) {
2930 r->setNeedsLayout(true, MarkOnlyThis);
2931 r->layoutIfNeeded();
2936 view()->layoutState()->m_columnInfo = columnInfo(); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
2939 void RenderBlock::markPositionedObjectsForLayout()
2941 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2942 if (positionedDescendants) {
2944 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2945 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2947 r->setChildNeedsLayout(true);
2952 void RenderBlock::markForPaginationRelayoutIfNeeded()
2954 ASSERT(!needsLayout());
2958 if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
2959 setChildNeedsLayout(true, MarkOnlyThis);
2962 void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
2964 // Repaint any overhanging floats (if we know we're the one to paint them).
2965 // Otherwise, bail out.
2966 if (!hasOverhangingFloats())
2969 // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
2970 // in this block. Better yet would be to push extra state for the containers of other floats.
2971 LayoutStateDisabler layoutStateDisabler(view());
2972 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2973 FloatingObjectSetIterator end = floatingObjectSet.end();
2974 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
2975 FloatingObject* r = *it;
2976 // Only repaint the object if it is overhanging, is not in its own layer, and
2977 // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
2978 // condition is replaced with being a descendant of us.
2979 if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
2980 r->m_renderer->repaint();
2981 r->m_renderer->repaintOverhangingFloats(false);
2986 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
2988 LayoutPoint adjustedPaintOffset = paintOffset + location();
2990 PaintPhase phase = paintInfo.phase;
2992 // Check if we need to do anything at all.
2993 // FIXME: Could eliminate the isRoot() check if we fix background painting so that the RenderView
2994 // paints the root's background.
2996 LayoutRect overflowBox = overflowRectForPaintRejection();
2997 flipForWritingMode(overflowBox);
2998 overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
2999 overflowBox.moveBy(adjustedPaintOffset);
3000 if (!overflowBox.intersects(paintInfo.rect))
3004 bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
3005 paintObject(paintInfo, adjustedPaintOffset);
3007 popContentsClip(paintInfo, phase, adjustedPaintOffset);
3009 // Our scrollbar widgets paint exactly when we tell them to, so that they work properly with
3010 // z-index. We paint after we painted the background/border, so that the scrollbars will
3011 // sit above the background/border.
3012 if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
3013 layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
3016 void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3018 if (paintInfo.context->paintingDisabled())
3021 const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
3022 bool ruleTransparent = style()->columnRuleIsTransparent();
3023 EBorderStyle ruleStyle = style()->columnRuleStyle();
3024 LayoutUnit ruleThickness = style()->columnRuleWidth();
3025 LayoutUnit colGap = columnGap();
3026 bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent;
3030 ColumnInfo* colInfo = columnInfo();
3031 unsigned colCount = columnCount(colInfo);
3033 bool antialias = shouldAntialiasLines(paintInfo.context);
3035 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3036 bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
3037 LayoutUnit currLogicalLeftOffset = leftToRight ? LayoutUnit() : contentLogicalWidth();
3038 LayoutUnit ruleAdd = logicalLeftOffsetForContent();
3039 LayoutUnit ruleLogicalLeft = leftToRight ? LayoutUnit() : contentLogicalWidth();
3040 LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
3041 BoxSide boxSide = isHorizontalWritingMode()
3042 ? leftToRight ? BSLeft : BSRight
3043 : leftToRight ? BSTop : BSBottom;
3045 for (unsigned i = 0; i < colCount; i++) {
3046 // Move to the next position.
3048 ruleLogicalLeft += inlineDirectionSize + colGap / 2;
3049 currLogicalLeftOffset += inlineDirectionSize + colGap;
3051 ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
3052 currLogicalLeftOffset -= (inlineDirectionSize + colGap);
3055 // Now paint the column rule.
3056 if (i < colCount - 1) {
3057 LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
3058 LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
3059 LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
3060 LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
3061 IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
3062 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3065 ruleLogicalLeft = currLogicalLeftOffset;
3068 bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
3069 LayoutUnit ruleLeft = isHorizontalWritingMode()
3070 ? borderLeft() + paddingLeft()
3071 : colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderAndPaddingBefore() : borderAndPaddingAfter());
3072 LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
3073 LayoutUnit ruleTop = isHorizontalWritingMode()
3074 ? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderAndPaddingBefore() : borderAndPaddingAfter())
3075 : borderStart() + paddingStart();
3076 LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
3077 LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
3080 if (isHorizontalWritingMode())
3081 ruleRect.setY(height() - ruleRect.maxY());
3083 ruleRect.setX(width() - ruleRect.maxX());
3086 ruleRect.moveBy(paintOffset);
3088 BoxSide boxSide = isHorizontalWritingMode()
3089 ? topToBottom ? BSTop : BSBottom
3090 : topToBottom ? BSLeft : BSRight;
3092 LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
3093 if (!isHorizontalWritingMode())
3094 step = step.transposedSize();
3096 for (unsigned i = 1; i < colCount; i++) {
3097 ruleRect.move(step);
3098 IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
3099 drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
3104 LayoutUnit RenderBlock::initialBlockOffsetForPainting() const
3106 ColumnInfo* colInfo = columnInfo();
3107 LayoutUnit result = 0;
3108 if (colInfo->progressionAxis() == ColumnInfo::BlockAxis && colInfo->progressionIsReversed()) {
3109 LayoutRect colRect = columnRectAt(colInfo, 0);
3110 result = isHorizontalWritingMode() ? colRect.y() : colRect.x();
3111 result -= borderAndPaddingBefore();
3112 if (style()->isFlippedBlocksWritingMode())
3118 LayoutUnit RenderBlock::blockDeltaForPaintingNextColumn() const
3120 ColumnInfo* colInfo = columnInfo();
3121 LayoutUnit blockDelta = -colInfo->columnHeight();
3122 LayoutUnit colGap = columnGap();
3123 if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
3124 if (!colInfo->progressionIsReversed())
3125 blockDelta = colGap;
3127 blockDelta -= (colInfo->columnHeight() + colGap);
3129 if (style()->isFlippedBlocksWritingMode())
3130 blockDelta = -blockDelta;
3134 void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
3136 // We need to do multiple passes, breaking up our child painting into strips.
3137 GraphicsContext* context = paintInfo.context;
3138 ColumnInfo* colInfo = columnInfo();
3139 unsigned colCount = columnCount(colInfo);
3142 LayoutUnit colGap = columnGap();
3143 LayoutUnit currLogicalTopOffset = initialBlockOffsetForPainting();
3144 LayoutUnit blockDelta = blockDeltaForPaintingNextColumn();
3145 for (unsigned i = 0; i < colCount; i++) {
3146 // For each rect, we clip to the rect, and then we adjust our coords.
3147 LayoutRect colRect = columnRectAt(colInfo, i);
3148 flipForWritingMode(colRect);
3150 LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
3151 LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
3152 colRect.moveBy(paintOffset);
3153 PaintInfo info(paintInfo);
3154 info.rect.intersect(pixelSnappedIntRect(colRect));
3156 if (!info.rect.isEmpty()) {
3157 GraphicsContextStateSaver stateSaver(*context);
3158 LayoutRect clipRect(colRect);
3160 if (i < colCount - 1) {
3161 if (isHorizontalWritingMode())
3162 clipRect.expand(colGap / 2, 0);
3164 clipRect.expand(0, colGap / 2);
3166 // Each strip pushes a clip, since column boxes are specified as being
3167 // like overflow:hidden.
3168 // FIXME: Content and column rules that extend outside column boxes at the edges of the multi-column element
3169 // are clipped according to the 'overflow' property.
3170 context->clip(pixelSnappedIntRect(clipRect));
3172 // Adjust our x and y when painting.
3173 LayoutPoint adjustedPaintOffset = paintOffset + offset;
3175 paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
3177 paintContents(info, adjustedPaintOffset);
3179 currLogicalTopOffset += blockDelta;
3183 void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3185 // Avoid painting descendants of the root element when stylesheets haven't loaded. This eliminates FOUC.
3186 // It's ok not to draw, because later on, when all the stylesheets do load, styleResolverChanged() on the Document
3187 // will do a full repaint.
3188 if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
3191 if (childrenInline())
3192 m_lineBoxes.paint(this, paintInfo, paintOffset);
3194 PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
3195 newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
3197 // We don't paint our own background, but we do let the kids paint their backgrounds.
3198 PaintInfo paintInfoForChild(paintInfo);
3199 paintInfoForChild.phase = newPhase;
3200 paintInfoForChild.updateSubtreePaintRootForChildren(this);
3202 // FIXME: Paint-time pagination is obsolete and is now only used by embedded WebViews inside AppKit
3203 // NSViews. Do not add any more code for this.
3204 bool usePrintRect = !view()->printRect().isEmpty();
3205 paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
3209 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3211 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
3212 if (!paintChild(child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
3217 bool RenderBlock::paintChild(RenderBox* child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
3219 // Check for page-break-before: always, and if it's set, break and bail.
3220 bool checkBeforeAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakBefore() == PBALWAYS);
3221 LayoutUnit absoluteChildY = paintOffset.y() + child->y();
3222 if (checkBeforeAlways
3223 && absoluteChildY > paintInfo.rect.y()
3224 && absoluteChildY < paintInfo.rect.maxY()) {
3225 view()->setBestTruncatedAt(absoluteChildY, this, true);
3229 RenderView* renderView = view();
3230 if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
3231 // Paginate block-level replaced elements.
3232 if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
3233 if (absoluteChildY < renderView->truncatedAt())
3234 renderView->setBestTruncatedAt(absoluteChildY, child);
3235 // If we were able to truncate, don't paint.
3236 if (absoluteChildY >= renderView->truncatedAt())
3241 LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
3242 if (!child->hasSelfPaintingLayer() && !child->isFloating())
3243 child->paint(paintInfoForChild, childPoint);
3245 // Check for page-break-after: always, and if it's set, break and bail.
3246 bool checkAfterAlways = !childrenInline() && (usePrintRect && child->style()->pageBreakAfter() == PBALWAYS);
3247 if (checkAfterAlways
3248 && (absoluteChildY + child->height()) > paintInfo.rect.y()
3249 && (absoluteChildY + child->height()) < paintInfo.rect.maxY()) {
3250 view()->setBestTruncatedAt(absoluteChildY + child->height() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
3257 void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
3259 // Paint the caret if the FrameSelection says so or if caret browsing is enabled
3260 bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
3261 RenderObject* caretPainter;
3262 bool isContentEditable;
3263 if (type == CursorCaret) {
3264 caretPainter = frame()->selection()->caretRenderer();
3265 isContentEditable = frame()->selection()->rendererIsEditable();
3267 caretPainter = frame()->page()->dragCaretController()->caretRenderer();
3268 isContentEditable = frame()->page()->dragCaretController()->isContentEditable();
3271 if (caretPainter == this && (isContentEditable || caretBrowsing)) {
3272 if (type == CursorCaret)
3273 frame()->selection()->paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
3275 frame()->page()->dragCaretController()->paintDragCaret(frame(), paintInfo.context, paintOffset, paintInfo.rect);
3279 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3281 PaintPhase paintPhase = paintInfo.phase;
3283 // 1. paint background, borders etc
3284 if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
3285 if (hasBoxDecorations())
3286 paintBoxDecorations(paintInfo, paintOffset);
3287 if (hasColumns() && !paintInfo.paintRootBackgroundOnly())
3288 paintColumnRules(paintInfo, paintOffset);
3291 if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
3292 paintMask(paintInfo, paintOffset);
3296 // We're done. We don't bother painting any children.
3297 if (paintPhase == PaintPhaseBlockBackground || paintInfo.paintRootBackgroundOnly())
3300 // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
3301 LayoutPoint scrolledOffset = paintOffset;
3302 if (hasOverflowClip())
3303 scrolledOffset.move(-scrolledContentOffset());
3305 // 2. paint contents
3306 if (paintPhase != PaintPhaseSelfOutline) {
3308 paintColumnContents(paintInfo, scrolledOffset);
3310 paintContents(paintInfo, scrolledOffset);
3313 // 3. paint selection
3314 // FIXME: Make this work with multi column layouts. For now don't fill gaps.
3315 bool isPrinting = document()->printing();
3316 if (!isPrinting && !hasColumns())
3317 paintSelection(paintInfo, scrolledOffset); // Fill in gaps in selection on lines and between blocks.
3320 if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
3322 paintColumnContents(paintInfo, scrolledOffset, true);
3324 paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
3327 // 5. paint outline.
3328 if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
3329 paintOutline(paintInfo, LayoutRect(paintOffset, size()));
3331 // 6. paint continuation outlines.
3332 if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
3333 RenderInline* inlineCont = inlineElementContinuation();
3334 if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
3335 RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->renderer());
3336 RenderBlock* cb = containingBlock();
3338 bool inlineEnclosedInSelfPaintingLayer = false;
3339 for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = box->parent()->enclosingBoxModelObject()) {
3340 if (box->hasSelfPaintingLayer()) {
3341 inlineEnclosedInSelfPaintingLayer = true;
3346 // Do not add continuations for outline painting by our containing block if we are a relative positioned
3347 // anonymous block (i.e. have our own layer), paint them straightaway instead. This is because a block depends on renderers in its continuation table being
3348 // in the same layer.
3349 if (!inlineEnclosedInSelfPaintingLayer && !hasLayer())
3350 cb->addContinuationWithOutline(inlineRenderer);
3351 else if (!inlineRenderer->firstLineBox() || (!inlineEnclosedInSelfPaintingLayer && hasLayer()))
3352 inlineRenderer->paintOutline(paintInfo, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
3354 paintContinuationOutlines(paintInfo, paintOffset);
3358 // If the caret's node's render object's containing block is this block, and the paint action is PaintPhaseForeground,
3359 // then paint the caret.
3360 if (paintPhase == PaintPhaseForeground) {
3361 paintCaret(paintInfo, paintOffset, CursorCaret);
3362 paintCaret(paintInfo, paintOffset, DragCaret);
3366 LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
3368 if (!style()->isFlippedBlocksWritingMode())
3371 // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
3372 // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
3374 if (isHorizontalWritingMode())
3375 return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
3376 return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
3379 void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
3381 if (!m_floatingObjects)
3384 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3385 FloatingObjectSetIterator end = floatingObjectSet.end();
3386 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3387 FloatingObject* r = *it;
3388 // Only paint the object if our m_shouldPaint flag is set.
3389 if (r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()) {
3390 PaintInfo currentPaintInfo(paintInfo);
3391 currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
3392 LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
3393 r->m_renderer->paint(currentPaintInfo, childPoint);
3394 if (!preservePhase) {
3395 currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
3396 r->m_renderer->paint(currentPaintInfo, childPoint);
3397 currentPaintInfo.phase = PaintPhaseFloat;
3398 r->m_renderer->paint(currentPaintInfo, childPoint);
3399 currentPaintInfo.phase = PaintPhaseForeground;
3400 r->m_renderer->paint(currentPaintInfo, childPoint);
3401 currentPaintInfo.phase = PaintPhaseOutline;
3402 r->m_renderer->paint(currentPaintInfo, childPoint);
3408 RenderInline* RenderBlock::inlineElementContinuation() const
3410 RenderBoxModelObject* continuation = this->continuation();
3411 return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
3414 RenderBlock* RenderBlock::blockElementContinuation() const
3416 RenderBoxModelObject* currentContinuation = continuation();
3417 if (!currentContinuation || currentContinuation->isInline())
3419 RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
3420 if (nextContinuation->isAnonymousBlock())
3421 return nextContinuation->blockElementContinuation();
3422 return nextContinuation;
3425 static ContinuationOutlineTableMap* continuationOutlineTable()
3427 DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
3431 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
3433 // We can't make this work if the inline is in a layer. We'll just rely on the broken
3435 ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
3437 ContinuationOutlineTableMap* table = continuationOutlineTable();
3438 ListHashSet<RenderInline*>* continuations = table->get(this);
3439 if (!continuations) {
3440 continuations = new ListHashSet<RenderInline*>;
3441 table->set(this, adoptPtr(continuations));
3444 continuations->add(flow);
3447 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
3449 ContinuationOutlineTableMap* table = continuationOutlineTable();
3450 if (table->isEmpty())
3453 ListHashSet<RenderInline*>* continuations = table->get(this);
3457 return continuations->contains(flow);
3460 void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
3462 ContinuationOutlineTableMap* table = continuationOutlineTable();
3463 if (table->isEmpty())
3466 OwnPtr<ListHashSet<RenderInline*> > continuations = table->take(this);
3470 LayoutPoint accumulatedPaintOffset = paintOffset;
3471 // Paint each continuation outline.
3472 ListHashSet<RenderInline*>::iterator end = continuations->end();
3473 for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
3474 // Need to add in the coordinates of the intervening blocks.
3475 RenderInline* flow = *it;
3476 RenderBlock* block = flow->containingBlock();
3477 for ( ; block && block != this; block = block->containingBlock())
3478 accumulatedPaintOffset.moveBy(block->location());
3480 flow->paintOutline(info, accumulatedPaintOffset);
3484 bool RenderBlock::shouldPaintSelectionGaps() const
3486 return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
3489 bool RenderBlock::isSelectionRoot() const
3491 if (isPseudoElement())
3493 ASSERT(node() || isAnonymous());
3495 // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
3499 if (isBody() || isRoot() || hasOverflowClip()
3500 || isPositioned() || isFloating()
3501 || isTableCell() || isInlineBlockOrInlineTable()
3502 || hasTransform() || hasReflection() || hasMask() || isWritingModeRoot()
3503 || isRenderFlowThread())
3506 if (view() && view()->selectionStart()) {
3507 Node* startElement = view()->selectionStart()->node();
3508 if (startElement && startElement->rootEditableElement() == node())
3515 GapRects RenderBlock::selectionGapRectsForRepaint(const RenderLayerModelObject* repaintContainer)
3517 ASSERT(!needsLayout());
3519 if (!shouldPaintSelectionGaps())
3522 TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
3523 mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip | UseTransforms);
3524 LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
3526 if (hasOverflowClip())
3527 offsetFromRepaintContainer -= scrolledContentOffset();
3529 LogicalSelectionOffsetCaches cache(this);
3530 LayoutUnit lastTop = 0;
3531 LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop, cache);
3532 LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop, cache);
3534 return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight, cache);
3537 void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
3539 if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
3540 LogicalSelectionOffsetCaches cache(this);
3541 LayoutUnit lastTop = 0;
3542 LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop, cache);
3543 LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop, cache);
3544 GraphicsContextStateSaver stateSaver(*paintInfo.context);
3546 LayoutRect gapRectsBounds = selectionGaps(this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, cache, &paintInfo);
3547 if (!gapRectsBounds.isEmpty()) {
3548 if (RenderLayer* layer = enclosingLayer()) {
3549 gapRectsBounds.moveBy(-paintOffset);
3551 LayoutRect localBounds(gapRectsBounds);
3552 flipForWritingMode(localBounds);
3553 gapRectsBounds = localToContainerQuad(FloatRect(localBounds), layer->renderer()).enclosingBoundingBox();
3554 if (layer->renderer()->hasOverflowClip())
3555 gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
3557 layer->addBlockSelectionGapsBounds(gapRectsBounds);
3563 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
3565 if (!positionedObjects)
3568 TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
3569 for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
3571 paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
3575 static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3577 return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
3580 static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
3582 return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
3585 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
3588 if (isHorizontalWritingMode())
3589 result = logicalRect;
3591 result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
3592 flipForWritingMode(result);
3593 result.moveBy(rootBlockPhysicalPosition);
3597 GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3598 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3600 // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
3601 // Clip out floating and positioned objects when painting selection gaps.
3603 // Note that we don't clip out overflow for positioned objects. We just stick to the border box.
3604 LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
3605 rootBlock->flipForWritingMode(flippedBlockRect);
3606 flippedBlockRect.moveBy(rootBlockPhysicalPosition);
3607 clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
3608 if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
3609 for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
3610 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
3611 if (m_floatingObjects) {
3612 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
3613 FloatingObjectSetIterator end = floatingObjectSet.end();
3614 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
3615 FloatingObject* r = *it;
3616 LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
3617 offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
3618 r->m_renderer->width(), r->m_renderer->height());
3619 rootBlock->flipForWritingMode(floatBox);
3620 floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
3621 paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
3626 // FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
3629 if (!isBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
3632 if (hasColumns() || hasTransform() || style()->columnSpan()) {
3633 // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
3634 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3635 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3636 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3640 if (childrenInline())
3641 result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
3643 result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
3645 // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
3646 if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd)) {
3647 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
3648 lastLogicalTop, lastLogicalLeft, lastLogicalRight, logicalHeight(), cache, paintInfo));
3654 GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3655 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3659 bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
3661 if (!firstLineBox()) {
3662 if (containsStart) {
3663 // Go ahead and update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this
3665 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
3666 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
3667 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
3672 RootInlineBox* lastSelectedLine = 0;
3673 RootInlineBox* curr;
3674 for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
3676 // Now paint the gaps for the lines.
3677 for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
3678 LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
3679 LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
3681 if (!containsStart && !lastSelectedLine &&
3682 selectionState() != SelectionStart && selectionState() != SelectionBoth)
3683 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, selTop, cache, paintInfo));
3685 LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
3686 logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
3687 LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
3688 if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
3689 || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
3690 result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, cache, paintInfo));
3692 lastSelectedLine = curr;
3695 if (containsStart && !lastSelectedLine)
3696 // VisibleSelection must start just after our last line.
3697 lastSelectedLine = lastRootBox();
3699 if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
3700 // Go ahead and update our lastY to be the bottom of the last selected line.
3701 lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
3702 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3703 lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom(), cache);
3708 GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
3709 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
3713 // Go ahead and jump right to the first block child that contains some selected objects.
3715 for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
3720 LogicalSelectionOffsetCaches childCache(this, cache);
3722 for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
3723 SelectionState childState = curr->selectionState();
3724 if (childState == SelectionBoth || childState == SelectionEnd)
3725 sawSelectionEnd = true;
3727 if (curr->isFloatingOrOutOfFlowPositioned())
3728 continue; // We must be a normal flow object in order to even be considered.
3730 if (curr->isInFlowPositioned() && curr->hasLayer()) {
3731 // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
3732 // Just disregard it completely.
3733 LayoutSize relOffset = curr->layer()->offsetForInFlowPosition();
3734 if (relOffset.width() || relOffset.height())
3738 bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
3739 bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
3740 if (fillBlockGaps) {
3741 // We need to fill the vertical gap above this object.
3742 if (childState == SelectionEnd || childState == SelectionInside) {
3743 // Fill the gap above the object.
3744 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,