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 "core/rendering/RenderBlock.h"
27 #include "core/HTMLNames.h"
28 #include "core/accessibility/AXObjectCache.h"
29 #include "core/dom/Document.h"
30 #include "core/dom/Element.h"
31 #include "core/dom/StyleEngine.h"
32 #include "core/dom/shadow/ShadowRoot.h"
33 #include "core/editing/Editor.h"
34 #include "core/editing/FrameSelection.h"
35 #include "core/events/OverflowEvent.h"
36 #include "core/fetch/ResourceLoadPriorityOptimizer.h"
37 #include "core/frame/FrameView.h"
38 #include "core/frame/LocalFrame.h"
39 #include "core/frame/Settings.h"
40 #include "core/page/Page.h"
41 #include "core/paint/BlockPainter.h"
42 #include "core/paint/BoxPainter.h"
43 #include "core/paint/DrawingRecorder.h"
44 #include "core/rendering/GraphicsContextAnnotator.h"
45 #include "core/rendering/HitTestLocation.h"
46 #include "core/rendering/HitTestResult.h"
47 #include "core/rendering/InlineIterator.h"
48 #include "core/rendering/InlineTextBox.h"
49 #include "core/rendering/PaintInfo.h"
50 #include "core/rendering/RenderCombineText.h"
51 #include "core/rendering/RenderDeprecatedFlexibleBox.h"
52 #include "core/rendering/RenderFlexibleBox.h"
53 #include "core/rendering/RenderFlowThread.h"
54 #include "core/rendering/RenderGrid.h"
55 #include "core/rendering/RenderInline.h"
56 #include "core/rendering/RenderLayer.h"
57 #include "core/rendering/RenderObjectInlines.h"
58 #include "core/rendering/RenderRegion.h"
59 #include "core/rendering/RenderTableCell.h"
60 #include "core/rendering/RenderTextControl.h"
61 #include "core/rendering/RenderTextFragment.h"
62 #include "core/rendering/RenderTheme.h"
63 #include "core/rendering/RenderView.h"
64 #include "core/rendering/TextAutosizer.h"
65 #include "core/rendering/shapes/ShapeOutsideInfo.h"
66 #include "core/rendering/style/ContentData.h"
67 #include "core/rendering/style/RenderStyle.h"
68 #include "platform/geometry/FloatQuad.h"
69 #include "platform/geometry/TransformState.h"
70 #include "platform/graphics/GraphicsContextCullSaver.h"
71 #include "platform/graphics/GraphicsContextStateSaver.h"
72 #include "wtf/StdLibExtras.h"
73 #include "wtf/TemporaryChange.h"
76 using namespace Unicode;
80 using namespace HTMLNames;
82 struct SameSizeAsRenderBlock : public RenderBox {
83 RenderObjectChildList children;
84 RenderLineBoxList lineBoxes;
85 int pageLogicalOffset;
89 COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
91 typedef WTF::HashMap<const RenderBox*, OwnPtr<ColumnInfo> > ColumnInfoMap;
92 static ColumnInfoMap* gColumnInfoMap = 0;
94 static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
95 static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
97 static TrackedContainerMap* gPositionedContainerMap = 0;
98 static TrackedContainerMap* gPercentHeightContainerMap = 0;
100 typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
101 static int gDelayUpdateScrollInfo = 0;
102 static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
104 static bool gColumnFlowSplitEnabled = true;
106 // This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
107 // only works on RenderBlocks. If this changes, this class should be shared with other RenderBoxes.
108 class OverflowEventDispatcher {
109 WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
111 OverflowEventDispatcher(const RenderBlock* block)
113 , m_hadHorizontalLayoutOverflow(false)
114 , m_hadVerticalLayoutOverflow(false)
116 m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
117 if (m_shouldDispatchEvent) {
118 m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
119 m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
123 ~OverflowEventDispatcher()
125 if (!m_shouldDispatchEvent)
128 bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
129 bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
131 bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
132 bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
134 if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
137 RefPtrWillBeRawPtr<OverflowEvent> event = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
138 event->setTarget(m_block->node());
139 m_block->document().enqueueAnimationFrameEvent(event.release());
143 const RenderBlock* m_block;
144 bool m_shouldDispatchEvent;
145 bool m_hadHorizontalLayoutOverflow;
146 bool m_hadVerticalLayoutOverflow;
149 RenderBlock::RenderBlock(ContainerNode* node)
151 , m_hasMarginBeforeQuirk(false)
152 , m_hasMarginAfterQuirk(false)
153 , m_beingDestroyed(false)
154 , m_hasMarkupTruncation(false)
155 , m_hasBorderOrPaddingLogicalWidthChanged(false)
156 , m_hasOnlySelfCollapsingChildren(false)
157 , m_descendantsWithFloatsMarkedForLayout(false)
159 // RenderBlockFlow calls setChildrenInline(true).
160 // By default, subclasses do not have inline children.
163 void RenderBlock::trace(Visitor* visitor)
165 visitor->trace(m_children);
166 RenderBox::trace(visitor);
169 static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
171 if (OwnPtr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
172 TrackedRendererListHashSet::iterator end = descendantSet->end();
173 for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
174 TrackedContainerMap::iterator it = containerMap->find(*descendant);
175 ASSERT(it != containerMap->end());
176 if (it == containerMap->end())
178 HashSet<RenderBlock*>* containerSet = it->value.get();
179 ASSERT(containerSet->contains(block));
180 containerSet->remove(block);
181 if (containerSet->isEmpty())
182 containerMap->remove(it);
187 static void appendImageIfNotNull(Vector<ImageResource*>& imageResources, const StyleImage* styleImage)
189 if (styleImage && styleImage->cachedImage()) {
190 ImageResource* imageResource = styleImage->cachedImage();
191 if (imageResource && !imageResource->isLoaded())
192 imageResources.append(styleImage->cachedImage());
196 static void appendLayers(Vector<ImageResource*>& images, const FillLayer& styleLayer)
198 for (const FillLayer* layer = &styleLayer; layer; layer = layer->next())
199 appendImageIfNotNull(images, layer->image());
202 static void appendImagesFromStyle(Vector<ImageResource*>& images, RenderStyle& blockStyle)
204 appendLayers(images, blockStyle.backgroundLayers());
205 appendLayers(images, blockStyle.maskLayers());
207 const ContentData* contentData = blockStyle.contentData();
208 if (contentData && contentData->isImage())
209 appendImageIfNotNull(images, toImageContentData(contentData)->image());
210 if (blockStyle.boxReflect())
211 appendImageIfNotNull(images, blockStyle.boxReflect()->mask().image());
212 appendImageIfNotNull(images, blockStyle.listStyleImage());
213 appendImageIfNotNull(images, blockStyle.borderImageSource());
214 appendImageIfNotNull(images, blockStyle.maskBoxImageSource());
215 if (blockStyle.shapeOutside())
216 appendImageIfNotNull(images, blockStyle.shapeOutside()->image());
219 void RenderBlock::removeFromGlobalMaps()
222 gColumnInfoMap->take(this);
223 if (gPercentHeightDescendantsMap)
224 removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
225 if (gPositionedDescendantsMap)
226 removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
229 RenderBlock::~RenderBlock()
232 removeFromGlobalMaps();
236 void RenderBlock::destroy()
238 RenderBox::destroy();
240 // RenderObject::removeChild called in destory() depends on gColumnInfoMap.
241 removeFromGlobalMaps();
245 void RenderBlock::willBeDestroyed()
247 // Mark as being destroyed to avoid trouble with merges in removeChild().
248 m_beingDestroyed = true;
250 // Make sure to destroy anonymous children first while they are still connected to the rest of the tree, so that they will
251 // properly dirty line boxes that they are removed from. Effects that do :before/:after only on hover could crash otherwise.
252 children()->destroyLeftoverChildren();
254 // Destroy our continuation before anything other than anonymous children.
255 // The reason we don't destroy it before anonymous children is that they may
256 // have continuations of their own that are anonymous children of our continuation.
257 RenderBoxModelObject* continuation = this->continuation();
259 continuation->destroy();
263 if (!documentBeingDestroyed()) {
264 if (firstLineBox()) {
265 // We can't wait for RenderBox::destroy to clear the selection,
266 // because by then we will have nuked the line boxes.
267 // FIXME: The FrameSelection should be responsible for this when it
268 // is notified of DOM mutations.
269 if (isSelectionBorder())
270 view()->clearSelection();
272 // If we are an anonymous block, then our line boxes might have children
273 // that will outlast this block. In the non-anonymous block case those
274 // children will be destroyed by the time we return from this function.
275 if (isAnonymousBlock()) {
276 for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
277 while (InlineBox* childBox = box->firstChild())
282 parent()->dirtyLinesFromChangedChild(this);
285 m_lineBoxes.deleteLineBoxes();
287 if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
288 gDelayedUpdateScrollInfoSet->remove(this);
290 if (TextAutosizer* textAutosizer = document().textAutosizer())
291 textAutosizer->destroy(this);
293 RenderBox::willBeDestroyed();
296 void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
298 RenderStyle* oldStyle = style();
300 setReplaced(newStyle.isDisplayInlineType());
302 if (oldStyle && parent()) {
303 bool oldStyleIsContainer = oldStyle->position() != StaticPosition || oldStyle->hasTransformRelatedProperty();
304 bool newStyleIsContainer = newStyle.position() != StaticPosition || newStyle.hasTransformRelatedProperty();
306 if (oldStyleIsContainer && !newStyleIsContainer) {
307 // Clear our positioned objects list. Our absolutely positioned descendants will be
308 // inserted into our containing block's positioned objects list during layout.
309 removePositionedObjects(0, NewContainingBlock);
310 } else if (!oldStyleIsContainer && newStyleIsContainer) {
311 // Remove our absolutely positioned descendants from their current containing block.
312 // They will be inserted into our positioned objects list during layout.
313 RenderObject* cb = parent();
314 while (cb && (cb->style()->position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
315 if (cb->style()->position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
316 cb = cb->containingBlock();
322 if (cb->isRenderBlock())
323 toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
327 RenderBox::styleWillChange(diff, newStyle);
330 static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
332 if (newStyle->isHorizontalWritingMode())
333 return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
334 || oldStyle->borderRightWidth() != newStyle->borderRightWidth()
335 || oldStyle->paddingLeft() != newStyle->paddingLeft()
336 || oldStyle->paddingRight() != newStyle->paddingRight();
338 return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
339 || oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
340 || oldStyle->paddingTop() != newStyle->paddingTop()
341 || oldStyle->paddingBottom() != newStyle->paddingBottom();
344 void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
346 RenderBox::styleDidChange(diff, oldStyle);
348 RenderStyle* newStyle = style();
350 if (!isAnonymousBlock()) {
351 // Ensure that all of our continuation blocks pick up the new style.
352 for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
353 RenderBoxModelObject* nextCont = currCont->continuation();
354 currCont->setContinuation(0);
355 currCont->setStyle(newStyle);
356 currCont->setContinuation(nextCont);
360 if (TextAutosizer* textAutosizer = document().textAutosizer())
361 textAutosizer->record(this);
363 propagateStyleToAnonymousChildren(true);
365 // It's possible for our border/padding to change, but for the overall logical width of the block to
366 // end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
367 m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff.needsFullLayout() && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
369 // If the style has unloaded images, want to notify the ResourceLoadPriorityOptimizer so that
370 // network priorities can be set.
371 Vector<ImageResource*> images;
372 appendImagesFromStyle(images, *newStyle);
373 if (images.isEmpty())
374 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->removeRenderObject(this);
376 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->addRenderObject(this);
379 void RenderBlock::invalidatePaintOfSubtreesIfNeeded(const PaintInvalidationState& childPaintInvalidationState)
381 RenderBox::invalidatePaintOfSubtreesIfNeeded(childPaintInvalidationState);
383 // Take care of positioned objects. This is required as PaintInvalidationState keeps a single clip rect.
384 if (TrackedRendererListHashSet* positionedObjects = this->positionedObjects()) {
385 TrackedRendererListHashSet::iterator end = positionedObjects->end();
386 for (TrackedRendererListHashSet::iterator it = positionedObjects->begin(); it != end; ++it) {
387 RenderBox* box = *it;
389 // One of the renderers we're skipping over here may be the child's paint invalidation container,
390 // so we can't pass our own paint invalidation container along.
391 const RenderLayerModelObject& paintInvalidationContainerForChild = *box->containerForPaintInvalidation();
393 // If it's a new paint invalidation container, we won't have properly accumulated the offset into the
394 // PaintInvalidationState.
395 // FIXME: Teach PaintInvalidationState to handle this case. crbug.com/371485
396 if (paintInvalidationContainerForChild != childPaintInvalidationState.paintInvalidationContainer()) {
397 ForceHorriblySlowRectMapping slowRectMapping(&childPaintInvalidationState);
398 PaintInvalidationState disabledPaintInvalidationState(childPaintInvalidationState, *this, paintInvalidationContainerForChild);
399 box->invalidateTreeIfNeeded(disabledPaintInvalidationState);
403 // If the positioned renderer is absolutely positioned and it is inside
404 // a relatively positioned inline element, we need to account for
405 // the inline elements position in PaintInvalidationState.
406 if (box->style()->position() == AbsolutePosition) {
407 RenderObject* container = box->container(&paintInvalidationContainerForChild, 0);
408 if (container->isRelPositioned() && container->isRenderInline()) {
409 // FIXME: We should be able to use PaintInvalidationState for this.
410 // Currently, we will place absolutely positioned elements inside
411 // relatively positioned inline blocks in the wrong location. crbug.com/371485
412 ForceHorriblySlowRectMapping slowRectMapping(&childPaintInvalidationState);
413 PaintInvalidationState disabledPaintInvalidationState(childPaintInvalidationState, *this, paintInvalidationContainerForChild);
414 box->invalidateTreeIfNeeded(disabledPaintInvalidationState);
419 box->invalidateTreeIfNeeded(childPaintInvalidationState);
424 RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
426 if (beforeChild && beforeChild->parent() == this)
429 RenderBlock* curr = toRenderBlock(continuation());
430 RenderBlock* nextToLast = this;
431 RenderBlock* last = this;
433 if (beforeChild && beforeChild->parent() == curr) {
434 if (curr->firstChild() == beforeChild)
441 curr = toRenderBlock(curr->continuation());
444 if (!beforeChild && !last->firstChild())
449 void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
451 RenderBlock* flow = continuationBefore(beforeChild);
452 ASSERT(!beforeChild || beforeChild->parent()->isAnonymousColumnSpanBlock() || beforeChild->parent()->isRenderBlock());
453 RenderBoxModelObject* beforeChildParent = 0;
455 beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
457 RenderBoxModelObject* cont = flow->continuation();
459 beforeChildParent = cont;
461 beforeChildParent = flow;
464 if (newChild->isFloatingOrOutOfFlowPositioned()) {
465 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
469 // A continuation always consists of two potential candidates: a block or an anonymous
470 // column span box holding column span children.
471 bool childIsNormal = newChild->isInline() || !newChild->style()->columnSpan();
472 bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style()->columnSpan();
473 bool flowIsNormal = flow->isInline() || !flow->style()->columnSpan();
475 if (flow == beforeChildParent) {
476 flow->addChildIgnoringContinuation(newChild, beforeChild);
480 // The goal here is to match up if we can, so that we can coalesce and create the
481 // minimal # of continuations needed for the inline.
482 if (childIsNormal == bcpIsNormal) {
483 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
486 if (flowIsNormal == childIsNormal) {
487 flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
490 beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
494 void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
496 ASSERT(!continuation()); // We don't yet support column spans that aren't immediate children of the multi-column block.
498 // The goal is to locate a suitable box in which to place our child.
499 RenderBlock* beforeChildParent = 0;
501 RenderObject* curr = beforeChild;
502 while (curr && curr->parent() != this)
503 curr = curr->parent();
504 beforeChildParent = toRenderBlock(curr);
505 ASSERT(beforeChildParent);
506 ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
508 beforeChildParent = toRenderBlock(lastChild());
510 // If the new child is floating or positioned it can just go in that block.
511 if (newChild->isFloatingOrOutOfFlowPositioned()) {
512 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
516 // See if the child can be placed in the box.
517 bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
518 bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
520 if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
521 beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
526 // Create a new block of the correct type.
527 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
528 children()->appendChildNode(this, newBox);
529 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
533 RenderObject* immediateChild = beforeChild;
534 bool isPreviousBlockViable = true;
535 while (immediateChild->parent() != this) {
536 if (isPreviousBlockViable)
537 isPreviousBlockViable = !immediateChild->previousSibling();
538 immediateChild = immediateChild->parent();
540 if (isPreviousBlockViable && immediateChild->previousSibling()) {
541 toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); // Treat like an append.
545 // Split our anonymous blocks.
546 RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
549 // Create a new anonymous box of the appropriate type.
550 RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
551 children()->insertChildNode(this, newBox, newBeforeChild);
552 newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
556 RenderBlockFlow* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
558 RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
559 for (RenderObject* curr = this; curr; curr = curr->parent()) {
560 if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isDocumentElement() || curr->isRenderView() || curr->hasOverflowClip()
561 || curr->isInlineBlockOrInlineTable())
564 // FIXME: Renderers that do special management of their children (tables, buttons,
565 // lists, flexboxes, etc.) breaks when the flow is split through them. Disabling
566 // multi-column for them to avoid this problem.)
567 if (!curr->isRenderBlockFlow() || curr->isListItem())
570 RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
571 if (!currBlock->createsAnonymousWrapper())
572 firstChildIgnoringAnonymousWrappers = currBlock;
574 if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
575 return toRenderBlockFlow(firstChildIgnoringAnonymousWrappers);
577 if (currBlock->isAnonymousColumnSpanBlock())
583 RenderBlock* RenderBlock::clone() const
585 RenderBlock* cloneBlock;
586 if (isAnonymousBlock()) {
587 cloneBlock = createAnonymousBlock();
588 cloneBlock->setChildrenInline(childrenInline());
591 RenderObject* cloneRenderer = toElement(node())->createRenderer(style());
592 cloneBlock = toRenderBlock(cloneRenderer);
593 cloneBlock->setStyle(style());
595 // This takes care of setting the right value of childrenInline in case
596 // generated content is added to cloneBlock and 'this' does not have
597 // generated content added yet.
598 cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
600 cloneBlock->setFlowThreadState(flowThreadState());
604 void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
605 RenderBlock* middleBlock,
606 RenderObject* beforeChild, RenderBoxModelObject* oldCont)
608 // Create a clone of this inline.
609 RenderBlock* cloneBlock = clone();
610 if (!isAnonymousBlock())
611 cloneBlock->setContinuation(oldCont);
613 if (!beforeChild && isAfterContent(lastChild()))
614 beforeChild = lastChild();
616 // If we are moving inline children from |this| to cloneBlock, then we need
617 // to clear our line box tree.
618 if (beforeChild && childrenInline())
621 // Now take all of the children from beforeChild to the end and remove
622 // them from |this| and place them in the clone.
623 moveChildrenTo(cloneBlock, beforeChild, 0, true);
625 // Hook |clone| up as the continuation of the middle block.
626 if (!cloneBlock->isAnonymousBlock())
627 middleBlock->setContinuation(cloneBlock);
629 // We have been reparented and are now under the fromBlock. We need
630 // to walk up our block parent chain until we hit the containing anonymous columns block.
631 // Once we hit the anonymous columns block we're done.
632 RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
633 RenderBoxModelObject* currChild = this;
634 RenderObject* currChildNextSibling = currChild->nextSibling();
636 while (curr && curr->isDescendantOf(fromBlock) && curr != fromBlock) {
637 ASSERT_WITH_SECURITY_IMPLICATION(curr->isRenderBlock());
639 RenderBlock* blockCurr = toRenderBlock(curr);
641 // Create a new clone.
642 RenderBlock* cloneChild = cloneBlock;
643 cloneBlock = blockCurr->clone();
645 // Insert our child clone as the first child.
646 cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
648 // Hook the clone up as a continuation of |curr|. Note we do encounter
649 // anonymous blocks possibly as we walk up the block chain. When we split an
650 // anonymous block, there's no need to do any continuation hookup, since we haven't
651 // actually split a real element.
652 if (!blockCurr->isAnonymousBlock()) {
653 oldCont = blockCurr->continuation();
654 blockCurr->setContinuation(cloneBlock);
655 cloneBlock->setContinuation(oldCont);
658 // Now we need to take all of the children starting from the first child
659 // *after* currChild and append them all to the clone.
660 blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
662 // Keep walking up the chain.
664 currChildNextSibling = currChild->nextSibling();
665 curr = toRenderBoxModelObject(curr->parent());
668 // Now we are at the columns block level. We need to put the clone into the toBlock.
669 toBlock->children()->appendChildNode(toBlock, cloneBlock);
671 // Now take all the children after currChild and remove them from the fromBlock
672 // and put them in the toBlock.
673 fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
676 void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
677 RenderObject* newChild, RenderBoxModelObject* oldCont)
679 RenderBlock* pre = 0;
680 RenderBlock* block = containingColumnsBlock();
682 // Delete our line boxes before we do the inline split into continuations.
683 block->deleteLineBoxTree();
685 bool madeNewBeforeBlock = false;
686 if (block->isAnonymousColumnsBlock()) {
687 // We can reuse this block and make it the preBlock of the next continuation.
689 pre->removePositionedObjects(0);
690 if (block->isRenderBlockFlow())
691 toRenderBlockFlow(pre)->removeFloatingObjects();
692 block = toRenderBlock(block->parent());
694 // No anonymous block available for use. Make one.
695 pre = block->createAnonymousColumnsBlock();
696 pre->setChildrenInline(false);
697 madeNewBeforeBlock = true;
700 RenderBlock* post = block->createAnonymousColumnsBlock();
701 post->setChildrenInline(false);
703 RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
704 if (madeNewBeforeBlock)
705 block->children()->insertChildNode(block, pre, boxFirst);
706 block->children()->insertChildNode(block, newBlockBox, boxFirst);
707 block->children()->insertChildNode(block, post, boxFirst);
708 block->setChildrenInline(false);
710 if (madeNewBeforeBlock)
711 block->moveChildrenTo(pre, boxFirst, 0, true);
713 splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
715 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
716 // time in makeChildrenNonInline by just setting this explicitly up front.
717 newBlockBox->setChildrenInline(false);
719 newBlockBox->addChild(newChild);
721 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
722 // get deleted properly. Because objects moves from the pre block into the post block, we want to
723 // make new line boxes instead of leaving the old line boxes around.
724 pre->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
725 block->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
726 post->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
729 void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlockFlow* newBlockBox, RenderObject* newChild)
731 RenderBlockFlow* pre = 0;
732 RenderBlockFlow* post = 0;
733 RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|. Assign to a variable
734 // so that we don't have to patch all of the rest of the code later on.
736 // Delete the block's line boxes before we do the split.
737 block->deleteLineBoxTree();
739 if (beforeChild && beforeChild->parent() != this)
740 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
742 if (beforeChild != firstChild()) {
743 pre = block->createAnonymousColumnsBlock();
744 pre->setChildrenInline(block->childrenInline());
748 post = block->createAnonymousColumnsBlock();
749 post->setChildrenInline(block->childrenInline());
752 RenderObject* boxFirst = block->firstChild();
754 block->children()->insertChildNode(block, pre, boxFirst);
755 block->children()->insertChildNode(block, newBlockBox, boxFirst);
757 block->children()->insertChildNode(block, post, boxFirst);
758 block->setChildrenInline(false);
760 // 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).
761 block->moveChildrenTo(pre, boxFirst, beforeChild, true);
762 block->moveChildrenTo(post, beforeChild, 0, true);
764 // We already know the newBlockBox isn't going to contain inline kids, so avoid wasting
765 // time in makeChildrenNonInline by just setting this explicitly up front.
766 newBlockBox->setChildrenInline(false);
768 newBlockBox->addChild(newChild);
770 // Always just do a full layout in order to ensure that line boxes (especially wrappers for images)
771 // get deleted properly. Because objects moved from the pre block into the post block, we want to
772 // make new line boxes instead of leaving the old line boxes around.
774 pre->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
775 block->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
777 post->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
780 RenderBlockFlow* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
782 // FIXME: This function is the gateway for the addition of column-span support. It will
783 // be added to in three stages:
784 // (1) Immediate children of a multi-column block can span.
785 // (2) Nested block-level children with only block-level ancestors between them and the multi-column block can span.
786 // (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
787 // cross the streams and have to cope with both types of continuations mixed together).
788 // This function currently supports (1) and (2).
789 RenderBlockFlow* columnsBlockAncestor = 0;
790 if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
791 && !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
792 columnsBlockAncestor = containingColumnsBlock(false);
793 if (columnsBlockAncestor) {
794 // Make sure that none of the parent ancestors have a continuation.
795 // If yes, we do not want split the block into continuations.
796 RenderObject* curr = this;
797 while (curr && curr != columnsBlockAncestor) {
798 if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
799 columnsBlockAncestor = 0;
802 curr = curr->parent();
806 return columnsBlockAncestor;
809 void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
811 if (beforeChild && beforeChild->parent() != this) {
812 RenderObject* beforeChildContainer = beforeChild->parent();
813 while (beforeChildContainer->parent() != this)
814 beforeChildContainer = beforeChildContainer->parent();
815 ASSERT(beforeChildContainer);
817 if (beforeChildContainer->isAnonymous()) {
818 // If the requested beforeChild is not one of our children, then this is because
819 // there is an anonymous container within this object that contains the beforeChild.
820 RenderObject* beforeChildAnonymousContainer = beforeChildContainer;
821 if (beforeChildAnonymousContainer->isAnonymousBlock()
822 // Full screen renderers and full screen placeholders act as anonymous blocks, not tables:
823 || beforeChildAnonymousContainer->isRenderFullScreen()
824 || beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
826 // Insert the child into the anonymous block box instead of here.
827 if (newChild->isInline() || newChild->isFloatingOrOutOfFlowPositioned() || beforeChild->parent()->slowFirstChild() != beforeChild)
828 beforeChild->parent()->addChild(newChild, beforeChild);
830 addChild(newChild, beforeChild->parent());
834 ASSERT(beforeChildAnonymousContainer->isTable());
835 if (newChild->isTablePart()) {
836 // Insert into the anonymous table.
837 beforeChildAnonymousContainer->addChild(newChild, beforeChild);
841 beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
843 ASSERT(beforeChild->parent() == this);
844 if (beforeChild->parent() != this) {
845 // We should never reach here. If we do, we need to use the
846 // safe fallback to use the topmost beforeChild container.
847 beforeChild = beforeChildContainer;
852 // Check for a spanning element in columns.
853 if (gColumnFlowSplitEnabled && !document().regionBasedColumnsEnabled()) {
854 RenderBlockFlow* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
855 if (columnsBlockAncestor) {
856 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
857 // We are placing a column-span element inside a block.
858 RenderBlockFlow* newBox = createAnonymousColumnSpanBlock();
860 if (columnsBlockAncestor != this && !isRenderFlowThread()) {
861 // We are nested inside a multi-column element and are being split by the span. We have to break up
862 // our block into continuations.
863 RenderBoxModelObject* oldContinuation = continuation();
865 // When we split an anonymous block, there's no need to do any continuation hookup,
866 // since we haven't actually split a real element.
867 if (!isAnonymousBlock())
868 setContinuation(newBox);
870 splitFlow(beforeChild, newBox, newChild, oldContinuation);
874 // We have to perform a split of this block's children. This involves creating an anonymous block box to hold
875 // the column-spanning |newChild|. We take all of the children from before |newChild| and put them into
876 // one anonymous columns block, and all of the children after |newChild| go into another anonymous block.
877 makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
882 bool madeBoxesNonInline = false;
884 // A block has to either have all of its children inline, or all of its children as blocks.
885 // So, if our children are currently inline and a block child has to be inserted, we move all our
886 // inline children into anonymous block boxes.
887 if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
888 // This is a block with inline content. Wrap the inline content in anonymous blocks.
889 makeChildrenNonInline(beforeChild);
890 madeBoxesNonInline = true;
892 if (beforeChild && beforeChild->parent() != this) {
893 beforeChild = beforeChild->parent();
894 ASSERT(beforeChild->isAnonymousBlock());
895 ASSERT(beforeChild->parent() == this);
897 } else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
898 // If we're inserting an inline child but all of our children are blocks, then we have to make sure
899 // it is put into an anomyous block box. We try to use an existing anonymous box if possible, otherwise
900 // a new one is created and inserted into our list of children in the appropriate position.
901 RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
903 if (afterChild && afterChild->isAnonymousBlock()) {
904 afterChild->addChild(newChild);
908 if (newChild->isInline()) {
909 // No suitable existing anonymous box - create a new one.
910 RenderBlock* newBox = createAnonymousBlock();
911 RenderBox::addChild(newBox, beforeChild);
912 newBox->addChild(newChild);
917 RenderBox::addChild(newChild, beforeChild);
919 if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
920 toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
921 // this object may be dead here
924 void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
926 if (continuation() && !isAnonymousBlock())
927 addChildToContinuation(newChild, beforeChild);
929 addChildIgnoringContinuation(newChild, beforeChild);
932 void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
934 if (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
935 addChildToAnonymousColumnBlocks(newChild, beforeChild);
937 addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
940 static void getInlineRun(RenderObject* start, RenderObject* boundary,
941 RenderObject*& inlineRunStart,
942 RenderObject*& inlineRunEnd)
944 // Beginning at |start| we find the largest contiguous run of inlines that
945 // we can. We denote the run with start and end points, |inlineRunStart|
946 // and |inlineRunEnd|. Note that these two values may be the same if
947 // we encounter only one inline.
949 // We skip any non-inlines we encounter as long as we haven't found any
952 // |boundary| indicates a non-inclusive boundary point. Regardless of whether |boundary|
953 // is inline or not, we will not include it in a run with inlines before it. It's as though we encountered
956 // Start by skipping as many non-inlines as we can.
957 RenderObject * curr = start;
960 while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
961 curr = curr->nextSibling();
963 inlineRunStart = inlineRunEnd = curr;
966 return; // No more inline children to be found.
968 sawInline = curr->isInline();
970 curr = curr->nextSibling();
971 while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
973 if (curr->isInline())
975 curr = curr->nextSibling();
977 } while (!sawInline);
980 void RenderBlock::deleteLineBoxTree()
982 ASSERT(!m_lineBoxes.firstLineBox());
985 void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
987 // makeChildrenNonInline takes a block whose children are *all* inline and it
988 // makes sure that inline children are coalesced under anonymous
989 // blocks. If |insertionPoint| is defined, then it represents the insertion point for
990 // the new block child that is causing us to have to wrap all the inlines. This
991 // means that we cannot coalesce inlines before |insertionPoint| with inlines following
992 // |insertionPoint|, because the new child is going to be inserted in between the inlines,
994 ASSERT(isInlineBlockOrInlineTable() || !isInline());
995 ASSERT(!insertionPoint || insertionPoint->parent() == this);
997 setChildrenInline(false);
999 RenderObject *child = firstChild();
1003 deleteLineBoxTree();
1006 RenderObject *inlineRunStart, *inlineRunEnd;
1007 getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
1009 if (!inlineRunStart)
1012 child = inlineRunEnd->nextSibling();
1014 RenderBlock* block = createAnonymousBlock();
1015 children()->insertChildNode(this, block, inlineRunStart);
1016 moveChildrenTo(block, inlineRunStart, child);
1020 for (RenderObject *c = firstChild(); c; c = c->nextSibling())
1021 ASSERT(!c->isInline());
1024 setShouldDoFullPaintInvalidation();
1027 void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
1029 ASSERT(child->isAnonymousBlock());
1030 ASSERT(!child->childrenInline());
1032 if (child->continuation() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
1035 RenderObject* firstAnChild = child->m_children.firstChild();
1036 RenderObject* lastAnChild = child->m_children.lastChild();
1038 RenderObject* o = firstAnChild;
1041 o = o->nextSibling();
1043 firstAnChild->setPreviousSibling(child->previousSibling());
1044 lastAnChild->setNextSibling(child->nextSibling());
1045 if (child->previousSibling())
1046 child->previousSibling()->setNextSibling(firstAnChild);
1047 if (child->nextSibling())
1048 child->nextSibling()->setPreviousSibling(lastAnChild);
1050 if (child == m_children.firstChild())
1051 m_children.setFirstChild(firstAnChild);
1052 if (child == m_children.lastChild())
1053 m_children.setLastChild(lastAnChild);
1055 if (child == m_children.firstChild())
1056 m_children.setFirstChild(child->nextSibling());
1057 if (child == m_children.lastChild())
1058 m_children.setLastChild(child->previousSibling());
1060 if (child->previousSibling())
1061 child->previousSibling()->setNextSibling(child->nextSibling());
1062 if (child->nextSibling())
1063 child->nextSibling()->setPreviousSibling(child->previousSibling());
1066 child->children()->setFirstChild(0);
1067 child->m_next = nullptr;
1069 // Remove all the information in the flow thread associated with the leftover anonymous block.
1070 child->removeFromRenderFlowThread();
1072 // RenderGrid keeps track of its children, we must notify it about changes in the tree.
1073 if (child->parent()->isRenderGrid())
1074 toRenderGrid(child->parent())->dirtyGrid();
1076 child->setParent(0);
1077 child->setPreviousSibling(0);
1078 child->setNextSibling(0);
1083 static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
1085 if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
1088 if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
1089 || (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
1092 if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
1093 || (next && (next->isRubyRun() || next->isRubyBase())))
1099 // Make sure the types of the anonymous blocks match up.
1100 return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
1101 && prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
1104 void RenderBlock::collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child)
1106 // It's possible that this block's destruction may have been triggered by the
1107 // child's removal. Just bail if the anonymous child block is already being
1108 // destroyed. See crbug.com/282088
1109 if (child->beingDestroyed())
1111 parent->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1112 parent->setChildrenInline(child->childrenInline());
1113 RenderObject* nextSibling = child->nextSibling();
1115 RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
1116 CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
1118 parent->children()->removeChildNode(parent, child, child->hasLayer());
1119 // FIXME: Get rid of the temporary disabling of continuations. This is needed by the old
1120 // multicol implementation, because of buggy block continuation handling (which is hard and
1121 // rather pointless to fix at this point). Support for block continuations can be removed
1122 // together with the old multicol implementation. crbug.com/408123
1123 RenderBoxModelObject* temporarilyInactiveContinuation = parent->continuation();
1124 if (temporarilyInactiveContinuation)
1125 parent->setContinuation(0);
1126 child->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
1127 if (temporarilyInactiveContinuation)
1128 parent->setContinuation(temporarilyInactiveContinuation);
1129 // Explicitly delete the child's line box tree, or the special anonymous
1130 // block handling in willBeDestroyed will cause problems.
1131 child->deleteLineBoxTree();
1135 void RenderBlock::removeChild(RenderObject* oldChild)
1137 // No need to waste time in merging or removing empty anonymous blocks.
1138 // We can just bail out if our document is getting destroyed.
1139 if (documentBeingDestroyed()) {
1140 RenderBox::removeChild(oldChild);
1144 // This protects against column split flows when anonymous blocks are getting merged.
1145 TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
1147 // If this child is a block, and if our previous and next siblings are
1148 // both anonymous blocks with inline content, then we can go ahead and
1149 // fold the inline content back together.
1150 RenderObject* prev = oldChild->previousSibling();
1151 RenderObject* next = oldChild->nextSibling();
1152 bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
1153 if (canMergeAnonymousBlocks && prev && next) {
1154 prev->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1155 RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
1156 RenderBlockFlow* prevBlock = toRenderBlockFlow(prev);
1158 if (prev->childrenInline() != next->childrenInline()) {
1159 RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
1160 RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
1162 // Place the inline children block inside of the block children block instead of deleting it.
1163 // In order to reuse it, we have to reset it to just be a generic anonymous block. Make sure
1164 // to clear out inherited column properties by just making a new style, and to also clear the
1165 // column span flag if it is set.
1166 ASSERT(!inlineChildrenBlock->continuation());
1167 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
1168 // Cache this value as it might get changed in setStyle() call.
1169 bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
1170 inlineChildrenBlock->setStyle(newStyle);
1171 children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
1173 // Now just put the inlineChildrenBlock inside the blockChildrenBlock.
1174 blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
1175 inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
1176 next->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation();
1178 // inlineChildrenBlock got reparented to blockChildrenBlock, so it is no longer a child
1179 // of "this". we null out prev or next so that is not used later in the function.
1180 if (inlineChildrenBlock == prevBlock)
1185 // Take all the children out of the |next| block and put them in
1186 // the |prev| block.
1187 nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
1189 // Delete the now-empty block's lines and nuke it.
1190 nextBlock->deleteLineBoxTree();
1191 nextBlock->destroy();
1196 RenderBox::removeChild(oldChild);
1198 RenderObject* child = prev ? prev : next;
1199 if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
1200 // The removal has knocked us down to containing only a single anonymous
1201 // box. We can go ahead and pull the content right back up into our
1203 collapseAnonymousBlockChild(this, toRenderBlock(child));
1204 } else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
1205 // It's possible that the removal has knocked us down to a single anonymous
1206 // block with pseudo-style element siblings (e.g. first-letter). If these
1207 // are floating, then we need to pull the content up also.
1208 RenderBlock* anonymousBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
1209 if ((anonymousBlock->previousSibling() || anonymousBlock->nextSibling())
1210 && (!anonymousBlock->previousSibling() || (anonymousBlock->previousSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->previousSibling()->isFloating() && !anonymousBlock->previousSibling()->previousSibling()))
1211 && (!anonymousBlock->nextSibling() || (anonymousBlock->nextSibling()->style()->styleType() != NOPSEUDO && anonymousBlock->nextSibling()->isFloating() && !anonymousBlock->nextSibling()->nextSibling()))) {
1212 collapseAnonymousBlockChild(this, anonymousBlock);
1216 if (!firstChild()) {
1217 // If this was our last child be sure to clear out our line boxes.
1218 if (childrenInline())
1219 deleteLineBoxTree();
1221 // If we are an empty anonymous block in the continuation chain,
1222 // we need to remove ourself and fix the continuation chain.
1223 if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild->isListMarker()) {
1224 RenderObject* containingBlockIgnoringAnonymous = containingBlock();
1225 while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymous())
1226 containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
1227 for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
1228 if (curr->virtualContinuation() != this)
1231 // Found our previous continuation. We just need to point it to
1232 // |this|'s next continuation.
1233 RenderBoxModelObject* nextContinuation = continuation();
1234 if (curr->isRenderInline())
1235 toRenderInline(curr)->setContinuation(nextContinuation);
1236 else if (curr->isRenderBlock())
1237 toRenderBlock(curr)->setContinuation(nextContinuation);
1239 ASSERT_NOT_REACHED();
1249 bool RenderBlock::isSelfCollapsingBlock() const
1251 // We are not self-collapsing if we
1252 // (a) have a non-zero height according to layout (an optimization to avoid wasting time)
1254 // (c) have border/padding,
1255 // (d) have a min-height
1256 // (e) have specified that one of our margins can't collapse using a CSS extension
1257 // (f) establish a new block formatting context.
1259 // The early exit must be done before we check for clean layout.
1260 // We should be able to give a quick answer if the box is a relayout boundary.
1261 // Being a relayout boundary implies a block formatting context, and also
1262 // our internal layout shouldn't affect our container in any way.
1263 if (createsBlockFormattingContext())
1266 // Placeholder elements are not laid out until the dimensions of their parent text control are known, so they
1267 // don't get layout until their parent has had layout - this is unique in the layout tree and means
1268 // when we call isSelfCollapsingBlock on them we find that they still need layout.
1269 ASSERT(!needsLayout() || (node() && node()->isElementNode() && toElement(node())->shadowPseudoId() == "-webkit-input-placeholder"));
1271 if (logicalHeight() > 0
1272 || isTable() || borderAndPaddingLogicalHeight()
1273 || style()->logicalMinHeight().isPositive()
1274 || style()->marginBeforeCollapse() == MSEPARATE || style()->marginAfterCollapse() == MSEPARATE)
1277 Length logicalHeightLength = style()->logicalHeight();
1278 bool hasAutoHeight = logicalHeightLength.isAuto();
1279 if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
1280 hasAutoHeight = true;
1281 for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
1282 if (cb->style()->logicalHeight().isFixed() || cb->isTableCell())
1283 hasAutoHeight = false;
1287 // If the height is 0 or auto, then whether or not we are a self-collapsing block depends
1288 // on whether we have content that is all self-collapsing or not.
1289 if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
1290 // If the block has inline children, see if we generated any line boxes. If we have any
1291 // line boxes, then we can't be self-collapsing, since we have content.
1292 if (childrenInline())
1293 return !firstLineBox();
1295 // Whether or not we collapse is dependent on whether all our normal flow children
1296 // are also self-collapsing.
1297 if (m_hasOnlySelfCollapsingChildren)
1299 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1300 if (child->isFloatingOrOutOfFlowPositioned())
1302 if (!child->isSelfCollapsingBlock())
1310 void RenderBlock::startDelayUpdateScrollInfo()
1312 if (gDelayUpdateScrollInfo == 0) {
1313 ASSERT(!gDelayedUpdateScrollInfoSet);
1314 gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
1316 ASSERT(gDelayedUpdateScrollInfoSet);
1317 ++gDelayUpdateScrollInfo;
1320 void RenderBlock::finishDelayUpdateScrollInfo()
1322 --gDelayUpdateScrollInfo;
1323 ASSERT(gDelayUpdateScrollInfo >= 0);
1324 if (gDelayUpdateScrollInfo == 0) {
1325 ASSERT(gDelayedUpdateScrollInfoSet);
1327 OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
1328 gDelayedUpdateScrollInfoSet = 0;
1330 for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
1331 RenderBlock* block = *it;
1332 if (block->hasOverflowClip()) {
1333 block->layer()->scrollableArea()->updateAfterLayout();
1339 void RenderBlock::updateScrollInfoAfterLayout()
1341 if (hasOverflowClip()) {
1342 if (style()->slowIsFlippedBlocksWritingMode()) {
1343 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=97937
1344 // Workaround for now. We cannot delay the scroll info for overflow
1345 // for items with opposite writing directions, as the contents needs
1346 // to overflow in that direction
1347 layer()->scrollableArea()->updateAfterLayout();
1351 if (gDelayUpdateScrollInfo)
1352 gDelayedUpdateScrollInfoSet->add(this);
1354 layer()->scrollableArea()->updateAfterLayout();
1358 void RenderBlock::layout()
1360 OverflowEventDispatcher dispatcher(this);
1362 // Update our first letter info now.
1363 updateFirstLetter();
1365 // Table cells call layoutBlock directly, so don't add any logic here. Put code into
1369 // It's safe to check for control clip here, since controls can never be table cells.
1370 // If we have a lightweight clip, there can never be any overflow from children.
1371 if (hasControlClip() && m_overflow)
1372 clearLayoutOverflow();
1374 invalidateBackgroundObscurationStatus();
1377 bool RenderBlock::updateImageLoadingPriorities()
1379 Vector<ImageResource*> images;
1380 appendImagesFromStyle(images, *style());
1382 if (images.isEmpty())
1385 LayoutRect viewBounds = viewRect();
1386 LayoutRect objectBounds = absoluteContentBox();
1387 // The object bounds might be empty right now, so intersects will fail since it doesn't deal
1388 // with empty rects. Use LayoutRect::contains in that case.
1390 if (!objectBounds.isEmpty())
1391 isVisible = viewBounds.intersects(objectBounds);
1393 isVisible = viewBounds.contains(objectBounds);
1395 ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
1396 ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
1398 LayoutRect screenArea;
1399 if (!objectBounds.isEmpty()) {
1400 screenArea = viewBounds;
1401 screenArea.intersect(objectBounds);
1404 for (Vector<ImageResource*>::iterator it = images.begin(), end = images.end(); it != end; ++it)
1405 ResourceLoadPriorityOptimizer::resourceLoadPriorityOptimizer()->notifyImageResourceVisibility(*it, status, screenArea);
1410 bool RenderBlock::widthAvailableToChildrenHasChanged()
1412 bool widthAvailableToChildrenHasChanged = m_hasBorderOrPaddingLogicalWidthChanged;
1413 m_hasBorderOrPaddingLogicalWidthChanged = false;
1415 // If we use border-box sizing, have percentage padding, and our parent has changed width then the width available to our children has changed even
1416 // though our own width has remained the same.
1417 widthAvailableToChildrenHasChanged |= style()->boxSizing() == BORDER_BOX && needsPreferredWidthsRecalculation() && view()->layoutState()->containingBlockLogicalWidthChanged();
1419 return widthAvailableToChildrenHasChanged;
1422 bool RenderBlock::updateLogicalWidthAndColumnWidth()
1424 LayoutUnit oldWidth = logicalWidth();
1425 LayoutUnit oldColumnWidth = desiredColumnWidth();
1427 updateLogicalWidth();
1430 return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth() || widthAvailableToChildrenHasChanged();
1433 void RenderBlock::layoutBlock(bool)
1435 ASSERT_NOT_REACHED();
1439 void RenderBlock::addOverflowFromChildren()
1441 if (!hasColumns()) {
1442 if (childrenInline())
1443 toRenderBlockFlow(this)->addOverflowFromInlineChildren();
1445 addOverflowFromBlockChildren();
1447 ColumnInfo* colInfo = columnInfo();
1448 if (columnCount(colInfo)) {
1449 LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
1450 addLayoutOverflow(lastRect);
1451 addContentsVisualOverflow(lastRect);
1456 void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
1460 // Add overflow from children.
1461 addOverflowFromChildren();
1463 // Add in the overflow from positioned objects.
1464 addOverflowFromPositionedObjects();
1466 if (hasOverflowClip()) {
1467 // When we have overflow clip, propagate the original spillout since it will include collapsed bottom margins
1468 // and bottom padding. Set the axis we don't care about to be 1, since we want this overflow to always
1469 // be considered reachable.
1470 LayoutRect clientRect(noOverflowRect());
1471 LayoutRect rectToApply;
1472 if (isHorizontalWritingMode())
1473 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
1475 rectToApply = LayoutRect(clientRect.x(), clientRect.y(), std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
1476 addLayoutOverflow(rectToApply);
1477 if (hasRenderOverflow())
1478 m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
1481 addVisualEffectOverflow();
1483 addVisualOverflowFromTheme();
1486 void RenderBlock::addOverflowFromBlockChildren()
1488 for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
1489 if (!child->isFloatingOrOutOfFlowPositioned())
1490 addOverflowFromChild(child);
1494 void RenderBlock::addOverflowFromPositionedObjects()
1496 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1497 if (!positionedDescendants)
1500 RenderBox* positionedObject;
1501 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1502 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1503 positionedObject = *it;
1505 // Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
1506 if (positionedObject->style()->position() != FixedPosition)
1507 addOverflowFromChild(positionedObject, LayoutSize(positionedObject->x(), positionedObject->y()));
1511 void RenderBlock::addVisualOverflowFromTheme()
1513 if (!style()->hasAppearance())
1516 IntRect inflatedRect = pixelSnappedBorderBoxRect();
1517 RenderTheme::theme().adjustPaintInvalidationRect(this, inflatedRect);
1518 addVisualOverflow(inflatedRect);
1521 bool RenderBlock::createsBlockFormattingContext() const
1523 return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || isFlexItemIncludingDeprecated()
1524 || style()->specifiesColumns() || isRenderFlowThread() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isDocumentElement() || style()->columnSpan();
1527 void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox* child)
1529 // FIXME: Technically percentage height objects only need a relayout if their percentage isn't going to be turned into
1530 // an auto value. Add a method to determine this, so that we can avoid the relayout.
1531 if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()))
1532 child->setChildNeedsLayout(MarkOnlyThis);
1534 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1535 if (relayoutChildren && child->needsPreferredWidthsRecalculation())
1536 child->setPreferredLogicalWidthsDirty(MarkOnlyThis);
1539 void RenderBlock::simplifiedNormalFlowLayout()
1541 if (childrenInline()) {
1542 ListHashSet<RootInlineBox*> lineBoxes;
1543 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1544 RenderObject* o = walker.current();
1545 if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
1546 o->layoutIfNeeded();
1547 if (toRenderBox(o)->inlineBoxWrapper()) {
1548 RootInlineBox& box = toRenderBox(o)->inlineBoxWrapper()->root();
1549 lineBoxes.add(&box);
1551 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1552 o->clearNeedsLayout();
1556 // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
1557 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1558 for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
1559 RootInlineBox* box = *it;
1560 box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
1563 for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
1564 if (!box->isOutOfFlowPositioned())
1565 box->layoutIfNeeded();
1570 bool RenderBlock::simplifiedLayout()
1572 // Check if we need to do a full layout.
1573 if (normalChildNeedsLayout() || selfNeedsLayout())
1576 // Check that we actually need to do a simplified layout.
1577 if (!posChildNeedsLayout() && !(needsSimplifiedNormalFlowLayout() || needsPositionedMovementLayout()))
1582 // LayoutState needs this deliberate scope to pop before paint invalidation.
1583 LayoutState state(*this, locationOffset());
1585 if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
1588 TextAutosizer::LayoutScope textAutosizerLayoutScope(this);
1590 // Lay out positioned descendants or objects that just need to recompute overflow.
1591 if (needsSimplifiedNormalFlowLayout())
1592 simplifiedNormalFlowLayout();
1594 // Lay out our positioned objects if our positioned child bit is set.
1595 // Also, if an absolute position element inside a relative positioned container moves, and the absolute element has a fixed position
1596 // child, neither the fixed element nor its container learn of the movement since posChildNeedsLayout() is only marked as far as the
1597 // relative positioned container. So if we can have fixed pos objects in our positioned objects list check if any of them
1598 // are statically positioned and thus need to move with their absolute ancestors.
1599 bool canContainFixedPosObjects = canContainFixedPositionObjects();
1600 if (posChildNeedsLayout() || needsPositionedMovementLayout() || canContainFixedPosObjects)
1601 layoutPositionedObjects(false, needsPositionedMovementLayout() ? ForcedLayoutAfterContainingBlockMoved : (!posChildNeedsLayout() && canContainFixedPosObjects ? LayoutOnlyFixedPositionedObjects : DefaultLayout));
1603 // Recompute our overflow information.
1604 // FIXME: We could do better here by computing a temporary overflow object from layoutPositionedObjects and only
1605 // updating our overflow if we either used to have overflow or if the new temporary object has overflow.
1606 // For now just always recompute overflow. This is no worse performance-wise than the old code that called rightmostPosition and
1607 // lowestPosition on every relayout so it's not a regression.
1608 // computeOverflow expects the bottom edge before we clamp our height. Since this information isn't available during
1609 // simplifiedLayout, we cache the value in m_overflow.
1610 LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
1611 computeOverflow(oldClientAfterEdge, true);
1614 updateLayerTransformAfterLayout();
1616 updateScrollInfoAfterLayout();
1622 void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope& layoutScope)
1624 if (child->style()->position() != FixedPosition)
1627 bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontalWritingMode());
1628 bool hasStaticInlinePosition = child->style()->hasStaticInlinePosition(isHorizontalWritingMode());
1629 if (!hasStaticBlockPosition && !hasStaticInlinePosition)
1632 RenderObject* o = child->parent();
1633 while (o && !o->isRenderView() && o->style()->position() != AbsolutePosition)
1635 if (o->style()->position() != AbsolutePosition)
1638 RenderBox* box = toRenderBox(child);
1639 if (hasStaticInlinePosition) {
1640 LogicalExtentComputedValues computedValues;
1641 box->computeLogicalWidth(computedValues);
1642 LayoutUnit newLeft = computedValues.m_position;
1643 if (newLeft != box->logicalLeft())
1644 layoutScope.setChildNeedsLayout(child);
1645 } else if (hasStaticBlockPosition) {
1646 LayoutUnit oldTop = box->logicalTop();
1647 box->updateLogicalHeight();
1648 if (box->logicalTop() != oldTop)
1649 layoutScope.setChildNeedsLayout(child);
1653 LayoutUnit RenderBlock::marginIntrinsicLogicalWidthForChild(RenderBox* child) const
1655 // A margin has three types: fixed, percentage, and auto (variable).
1656 // Auto and percentage margins become 0 when computing min/max width.
1657 // Fixed margins can be added in as is.
1658 Length marginLeft = child->style()->marginStartUsing(style());
1659 Length marginRight = child->style()->marginEndUsing(style());
1660 LayoutUnit margin = 0;
1661 if (marginLeft.isFixed())
1662 margin += marginLeft.value();
1663 if (marginRight.isFixed())
1664 margin += marginRight.value();
1668 void RenderBlock::layoutPositionedObjects(bool relayoutChildren, PositionedLayoutBehavior info)
1670 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
1671 if (!positionedDescendants)
1675 view()->layoutState()->clearPaginationInformation(); // Positioned objects are not part of the column flow, so they don't paginate with the columns.
1678 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1679 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
1682 r->setMayNeedPaintInvalidation(true);
1684 SubtreeLayoutScope layoutScope(*r);
1685 // A fixed position element with an absolute positioned ancestor has no way of knowing if the latter has changed position. So
1686 // 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.
1687 // it has static position.
1688 markFixedPositionObjectForLayoutIfNeeded(r, layoutScope);
1689 if (info == LayoutOnlyFixedPositionedObjects) {
1690 r->layoutIfNeeded();
1694 // When a non-positioned block element moves, it may have positioned children that are implicitly positioned relative to the
1695 // non-positioned block. Rather than trying to detect all of these movement cases, we just always lay out positioned
1696 // objects that are positioned implicitly like this. Such objects are rare, and so in typical DHTML menu usage (where everything is
1697 // positioned explicitly) this should not incur a performance penalty.
1698 if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
1699 layoutScope.setChildNeedsLayout(r);
1701 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1702 if (relayoutChildren && r->needsPreferredWidthsRecalculation())
1703 r->setPreferredLogicalWidthsDirty(MarkOnlyThis);
1705 if (!r->needsLayout())
1706 r->markForPaginationRelayoutIfNeeded(layoutScope);
1708 // If we are paginated or in a line grid, go ahead and compute a vertical position for our object now.
1709 // If it's wrong we'll lay out again.
1710 LayoutUnit oldLogicalTop = 0;
1711 bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
1712 if (needsBlockDirectionLocationSetBeforeLayout) {
1713 if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
1714 r->updateLogicalHeight();
1716 r->updateLogicalWidth();
1717 oldLogicalTop = logicalTopForChild(r);
1720 // FIXME: We should be able to do a r->setNeedsPositionedMovementLayout() here instead of a full layout. Need
1721 // to investigate why it does not trigger the correct invalidations in that case. crbug.com/350756
1722 if (info == ForcedLayoutAfterContainingBlockMoved)
1723 r->setNeedsLayout();
1725 r->layoutIfNeeded();
1727 // Lay out again if our estimate was wrong.
1728 if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop)
1729 r->forceChildLayout();
1733 view()->layoutState()->setColumnInfo(columnInfo()); // FIXME: Kind of gross. We just put this back into the layout state so that pop() will work.
1736 void RenderBlock::markPositionedObjectsForLayout()
1738 if (TrackedRendererListHashSet* positionedDescendants = positionedObjects()) {
1739 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
1740 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it)
1741 (*it)->setChildNeedsLayout();
1745 void RenderBlock::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutScope)
1747 ASSERT(!needsLayout());
1751 if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(*this, logicalTop()) != pageLogicalOffset()))
1752 layoutScope.setChildNeedsLayout(this);
1755 void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1757 BlockPainter(*this).paint(paintInfo, paintOffset);
1760 void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1762 BlockPainter(*this).paintChildren(paintInfo, paintOffset);
1765 void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1767 BlockPainter(*this).paintObject(paintInfo, paintOffset);
1770 RenderInline* RenderBlock::inlineElementContinuation() const
1772 RenderBoxModelObject* continuation = this->continuation();
1773 return continuation && continuation->isInline() ? toRenderInline(continuation) : 0;
1776 RenderBlock* RenderBlock::blockElementContinuation() const
1778 RenderBoxModelObject* currentContinuation = continuation();
1779 if (!currentContinuation || currentContinuation->isInline())
1781 RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
1782 if (nextContinuation->isAnonymousBlock())
1783 return nextContinuation->blockElementContinuation();
1784 return nextContinuation;
1787 ContinuationOutlineTableMap* continuationOutlineTable()
1789 DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
1793 void RenderBlock::addContinuationWithOutline(RenderInline* flow)
1795 // We can't make this work if the inline is in a layer. We'll just rely on the broken
1797 ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
1799 ContinuationOutlineTableMap* table = continuationOutlineTable();
1800 ListHashSet<RenderInline*>* continuations = table->get(this);
1801 if (!continuations) {
1802 continuations = new ListHashSet<RenderInline*>;
1803 table->set(this, adoptPtr(continuations));
1806 continuations->add(flow);
1809 bool RenderBlock::shouldPaintSelectionGaps() const
1811 return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
1814 bool RenderBlock::isSelectionRoot() const
1816 if (isPseudoElement())
1818 ASSERT(node() || isAnonymous());
1820 // FIXME: Eventually tables should have to learn how to fill gaps between cells, at least in simple non-spanning cases.
1824 if (isBody() || isDocumentElement() || hasOverflowClip()
1825 || isPositioned() || isFloating()
1826 || isTableCell() || isInlineBlockOrInlineTable()
1827 || hasTransformRelatedProperty() || hasReflection() || hasMask() || isWritingModeRoot()
1828 || isRenderFlowThread() || isFlexItemIncludingDeprecated())
1831 if (view() && view()->selectionStart()) {
1832 Node* startElement = view()->selectionStart()->node();
1833 if (startElement && startElement->rootEditableElement() == node())
1840 GapRects RenderBlock::selectionGapRectsForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer) const
1842 ASSERT(!needsLayout());
1844 if (!shouldPaintSelectionGaps())
1847 TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
1848 mapLocalToContainer(paintInvalidationContainer, transformState, ApplyContainerFlip | UseTransforms);
1849 LayoutPoint offsetFromPaintInvalidationContainer = roundedLayoutPoint(transformState.mappedPoint());
1851 if (hasOverflowClip())
1852 offsetFromPaintInvalidationContainer -= scrolledContentOffset();
1854 LayoutUnit lastTop = 0;
1855 LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
1856 LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
1858 return selectionGaps(this, offsetFromPaintInvalidationContainer, IntSize(), lastTop, lastLeft, lastRight);
1861 static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
1863 if (!positionedObjects)
1866 TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
1867 for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
1869 paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
1873 LayoutUnit RenderBlock::blockDirectionOffset(const LayoutSize& offsetFromBlock) const
1875 return isHorizontalWritingMode() ? offsetFromBlock.height() : offsetFromBlock.width();
1878 LayoutUnit RenderBlock::inlineDirectionOffset(const LayoutSize& offsetFromBlock) const
1880 return isHorizontalWritingMode() ? offsetFromBlock.width() : offsetFromBlock.height();
1883 LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect) const
1886 if (isHorizontalWritingMode())
1887 result = logicalRect;
1889 result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
1890 flipForWritingMode(result);
1891 result.moveBy(rootBlockPhysicalPosition);
1895 GapRects RenderBlock::selectionGaps(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1896 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo) const
1898 // IMPORTANT: Callers of this method that intend for painting to happen need to do a save/restore.
1899 // Clip out floating and positioned objects when painting selection gaps.
1901 // Note that we don't clip out overflow for positioned objects. We just stick to the border box.
1902 LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
1903 rootBlock->flipForWritingMode(flippedBlockRect);
1904 flippedBlockRect.moveBy(rootBlockPhysicalPosition);
1905 clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
1906 if (isBody() || isDocumentElement()) // The <body> must make sure to examine its containingBlock's positioned objects.
1907 for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
1908 clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
1909 clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
1912 // 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
1915 if (!isRenderBlockFlow()) // FIXME: Make multi-column selection gap filling work someday.
1918 if (hasColumns() || hasTransformRelatedProperty() || style()->columnSpan()) {
1919 // FIXME: We should learn how to gap fill multiple columns and transforms eventually.
1920 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
1921 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
1922 lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
1926 if (childrenInline())
1927 result = toRenderBlockFlow(this)->inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
1929 result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
1931 // Go ahead and fill the vertical gap all the way to the bottom of our block if the selection extends past our block.
1932 if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
1933 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
1934 logicalHeight(), paintInfo));
1938 GapRects RenderBlock::blockSelectionGaps(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
1939 LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo) const
1943 // Go ahead and jump right to the first block child that contains some selected objects.
1945 for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
1947 for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
1948 SelectionState childState = curr->selectionState();
1949 if (childState == SelectionBoth || childState == SelectionEnd)
1950 sawSelectionEnd = true;
1952 if (curr->isFloatingOrOutOfFlowPositioned())
1953 continue; // We must be a normal flow object in order to even be considered.
1955 if (curr->isRelPositioned() && curr->hasLayer()) {
1956 // If the relposition offset is anything other than 0, then treat this just like an absolute positioned element.
1957 // Just disregard it completely.
1958 LayoutSize relOffset = curr->layer()->offsetForInFlowPosition();
1959 if (relOffset.width() || relOffset.height())
1963 bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); // FIXME: Eventually we won't special-case table like this.
1964 bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
1965 if (fillBlockGaps) {
1966 // We need to fill the vertical gap above this object.
1967 if (childState == SelectionEnd || childState == SelectionInside)
1968 // Fill the gap above the object.
1969 result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
1970 curr->logicalTop(), paintInfo));
1972 // Only fill side gaps for objects that paint their own selection if we know for sure the selection is going to extend all the way *past*
1973 // our object. We know this if the selection did not end inside our object.
1974 if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
1975 childState = SelectionNone;
1977 // Fill side gaps on this object based off its state.
1978 bool leftGap, rightGap;
1979 getSelectionGapInfo(childState, leftGap, rightGap);
1982 result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
1984 result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
1986 // Update lastLogicalTop to be just underneath the object. lastLogicalLeft and lastLogicalRight extend as far as
1987 // they can without bumping into floating or positioned objects. Ideally they will go right up
1988 // to the border of the root selection block.
1989 lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + curr->logicalBottom();
1990 lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
1991 lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
1992 } else if (childState != SelectionNone)
1993 // We must be a block that has some selected object inside it. Go ahead and recur.
1994 result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()),
1995 lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
2000 IntRect alignSelectionRectToDevicePixels(LayoutRect& rect)
2002 LayoutUnit roundedX = rect.x().round();
2003 return IntRect(roundedX, rect.y().round(),
2004 (rect.maxX() - roundedX).round(),
2005 snapSizeToPixel(rect.height(), rect.y()));
2008 LayoutRect RenderBlock::blockSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2009 LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo) const
2011 LayoutUnit logicalTop = lastLogicalTop;
2012 LayoutUnit logicalHeight = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalBottom - logicalTop;
2013 if (logicalHeight <= 0)
2014 return LayoutRect();
2016 // Get the selection offsets for the bottom of the gap
2017 LayoutUnit logicalLeft = std::max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
2018 LayoutUnit logicalRight = std::min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
2019 LayoutUnit logicalWidth = logicalRight - logicalLeft;
2020 if (logicalWidth <= 0)
2021 return LayoutRect();
2023 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
2025 IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2026 DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2027 paintInfo->context->fillRect(selectionGapRect, selectionBackgroundColor());
2032 LayoutRect RenderBlock::logicalLeftSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2033 const RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo) const
2035 LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
2036 LayoutUnit rootBlockLogicalLeft = std::max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
2037 LayoutUnit rootBlockLogicalRight = std::min(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + logicalLeft, std::min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2038 LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2039 if (rootBlockLogicalWidth <= 0)
2040 return LayoutRect();
2042 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2044 IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2045 DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2046 paintInfo->context->fillRect(selectionGapRect, selObj->selectionBackgroundColor());
2051 LayoutRect RenderBlock::logicalRightSelectionGap(const RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
2052 const RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo) const
2054 LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
2055 LayoutUnit rootBlockLogicalLeft = std::max(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
2056 LayoutUnit rootBlockLogicalRight = std::min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
2057 LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
2058 if (rootBlockLogicalWidth <= 0)
2059 return LayoutRect();
2061 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
2063 IntRect selectionGapRect = alignSelectionRectToDevicePixels(gapRect);
2064 DrawingRecorder recorder(paintInfo->context, this, paintInfo->phase, selectionGapRect);
2065 paintInfo->context->fillRect(selectionGapRect, selObj->selectionBackgroundColor());
2070 void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap) const
2072 bool ltr = style()->isLeftToRightDirection();
2073 leftGap = (state == RenderObject::SelectionInside) ||
2074 (state == RenderObject::SelectionEnd && ltr) ||
2075 (state == RenderObject::SelectionStart && !ltr);
2076 rightGap = (state == RenderObject::SelectionInside) ||
2077 (state == RenderObject::SelectionStart && ltr) ||
2078 (state == RenderObject::SelectionEnd && !ltr);
2081 LayoutUnit RenderBlock::logicalLeftSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2083 // The border can potentially be further extended by our containingBlock().
2084 if (rootBlock != this)
2085 return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
2086 return logicalLeftOffsetForContent();
2089 LayoutUnit RenderBlock::logicalRightSelectionOffset(const RenderBlock* rootBlock, LayoutUnit position) const
2091 // The border can potentially be further extended by our containingBlock().
2092 if (rootBlock != this)
2093 return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
2094 return logicalRightOffsetForContent();
2097 RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
2099 if (isSelectionRoot())
2102 const RenderObject* object = this;
2103 RenderObject* sibling;
2105 sibling = object->previousSibling();
2106 while (sibling && (!sibling->isRenderBlock() || toRenderBlock(sibling)->isSelectionRoot()))
2107 sibling = sibling->previousSibling();
2109 offset -= LayoutSize(toRenderBlock(object)->logicalLeft(), toRenderBlock(object)->logicalTop());
2110 object = object->parent();
2111 } while (!sibling && object && object->isRenderBlock() && !toRenderBlock(object)->isSelectionRoot());
2116 RenderBlock* beforeBlock = toRenderBlock(sibling);
2118 offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2120 RenderObject* child = beforeBlock->lastChild();
2121 while (child && child->isRenderBlock()) {
2122 beforeBlock = toRenderBlock(child);
2123 offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
2124 child = beforeBlock->lastChild();
2129 void RenderBlock::setSelectionState(SelectionState state)
2131 RenderBox::setSelectionState(state);
2133 if (inlineBoxWrapper() && canUpdateSelectionOnRootLineBoxes())
2134 inlineBoxWrapper()->root().setHasSelectedChildren(state != SelectionNone);
2137 void RenderBlock::insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2139 if (!descendantsMap) {
2140 descendantsMap = new TrackedDescendantsMap;
2141 containerMap = new TrackedContainerMap;
2144 TrackedRendererListHashSet* descendantSet = descendantsMap->get(this);
2145 if (!descendantSet) {
2146 descendantSet = new TrackedRendererListHashSet;
2147 descendantsMap->set(this, adoptPtr(descendantSet));
2149 bool added = descendantSet->add(descendant).isNewEntry;
2151 ASSERT(containerMap->get(descendant));
2152 ASSERT(containerMap->get(descendant)->contains(this));
2156 HashSet<RenderBlock*>* containerSet = containerMap->get(descendant);
2157 if (!containerSet) {
2158 containerSet = new HashSet<RenderBlock*>;
2159 containerMap->set(descendant, adoptPtr(containerSet));
2161 ASSERT(!containerSet->contains(this));
2162 containerSet->add(this);
2165 void RenderBlock::removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
2167 if (!descendantsMap)
2170 OwnPtr<HashSet<RenderBlock*> > containerSet = containerMap->take(descendant);
2174 HashSet<RenderBlock*>::iterator end = containerSet->end();
2175 for (HashSet<RenderBlock*>::iterator it = containerSet->begin(); it != end; ++it) {
2176 RenderBlock* container = *it;
2178 // FIXME: Disabling this assert temporarily until we fix the layout
2179 // bugs associated with positioned objects not properly cleared from
2180 // their ancestor chain before being moved. See webkit bug 93766.
2181 // ASSERT(descendant->isDescendantOf(container));
2183 TrackedDescendantsMap::iterator descendantsMapIterator = descendantsMap->find(container);
2184 ASSERT(descendantsMapIterator != descendantsMap->end());
2185 if (descendantsMapIterator == descendantsMap->end())
2187 TrackedRendererListHashSet* descendantSet = descendantsMapIterator->value.get();
2188 ASSERT(descendantSet->contains(descendant));
2189 descendantSet->remove(descendant);
2190 if (descendantSet->isEmpty())
2191 descendantsMap->remove(descendantsMapIterator);
2195 TrackedRendererListHashSet* RenderBlock::positionedObjects() const
2197 if (gPositionedDescendantsMap)
2198 return gPositionedDescendantsMap->get(this);
2202 void RenderBlock::insertPositionedObject(RenderBox* o)
2204 ASSERT(!isAnonymousBlock());
2206 if (o->isRenderFlowThread())
2209 insertIntoTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2212 void RenderBlock::removePositionedObject(RenderBox* o)
2214 removeFromTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
2217 void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState containingBlockState)
2219 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
2220 if (!positionedDescendants)
2225 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
2227 Vector<RenderBox*, 16> deadObjects;
2229 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
2231 if (!o || r->isDescendantOf(o)) {
2232 if (containingBlockState == NewContainingBlock) {
2233 r->setChildNeedsLayout(MarkOnlyThis);
2234 if (r->needsPreferredWidthsRecalculation())
2235 r->setPreferredLogicalWidthsDirty(MarkOnlyThis);
2238 // It is parent blocks job to add positioned child to positioned objects list of its containing block
2239 // Parent layout needs to be invalidated to ensure this happens.
2240 RenderObject* p = r->parent();
2241 while (p && !p->isRenderBlock())
2244 p->setChildNeedsLayout();
2246 deadObjects.append(r);
2250 for (unsigned i = 0; i < deadObjects.size(); i++)
2251 removePositionedObject(deadObjects.at(i));
2254 void RenderBlock::addPercentHeightDescendant(RenderBox* descendant)
2256 insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2259 void RenderBlock::removePercentHeightDescendant(RenderBox* descendant)
2261 removeFromTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
2264 TrackedRendererListHashSet* RenderBlock::percentHeightDescendants() const
2266 return gPercentHeightDescendantsMap ? gPercentHeightDescendantsMap->get(this) : 0;
2269 bool RenderBlock::hasPercentHeightContainerMap()
2271 return gPercentHeightContainerMap;
2274 bool RenderBlock::hasPercentHeightDescendant(RenderBox* descendant)
2276 // We don't null check gPercentHeightContainerMap since the caller
2277 // already ensures this and we need to call this function on every
2278 // descendant in clearPercentHeightDescendantsFrom().
2279 ASSERT(gPercentHeightContainerMap);
2280 return gPercentHeightContainerMap->contains(descendant);
2283 void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope& layoutScope)
2285 if (!gPercentHeightDescendantsMap)
2288 TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
2292 TrackedRendererListHashSet::iterator end = descendants->end();
2293 for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
2294 RenderBox* box = *it;
2295 while (box != this) {
2296 if (box->normalChildNeedsLayout())
2298 layoutScope.setChildNeedsLayout(box);
2299 box = box->containingBlock();
2307 void RenderBlock::removePercentHeightDescendantIfNeeded(RenderBox* descendant)
2309 // We query the map directly, rather than looking at style's
2310 // logicalHeight()/logicalMinHeight()/logicalMaxHeight() since those
2311 // can change with writing mode/directional changes.
2312 if (!hasPercentHeightContainerMap())
2315 if (!hasPercentHeightDescendant(descendant))
2318 removePercentHeightDescendant(descendant);
2321 void RenderBlock::clearPercentHeightDescendantsFrom(RenderBox* parent)
2323 ASSERT(gPercentHeightContainerMap);
2324 for (RenderObject* curr = parent->slowFirstChild(); curr; curr = curr->nextInPreOrder(parent)) {
2328 RenderBox* box = toRenderBox(curr);
2329 if (!hasPercentHeightDescendant(box))
2332 removePercentHeightDescendant(box);
2336 LayoutUnit RenderBlock::textIndentOffset() const
2339 if (style()->textIndent().isPercent())
2340 cw = containingBlock()->availableLogicalWidth();
2341 return minimumValueForLength(style()->textIndent(), cw);
2344 void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
2346 if (logicalTop >= logicalBottom)
2349 RootInlineBox* lowestDirtyLine = lastRootBox();
2350 RootInlineBox* afterLowest = lowestDirtyLine;
2351 while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < LayoutUnit::max()) {
2352 afterLowest = lowestDirtyLine;
2353 lowestDirtyLine = lowestDirtyLine->prevRootBox();
2356 while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
2357 afterLowest->markDirty();
2358 afterLowest = afterLowest->prevRootBox();
2362 bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
2364 if (!scrollsOverflow())
2367 return layer()->scrollableArea()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
2370 Node* RenderBlock::nodeForHitTest() const
2372 // If we are in the margins of block elements that are part of a
2373 // continuation we're actually still inside the enclosing element
2374 // that was split. Use the appropriate inner node.
2375 return isAnonymousBlockContinuation() ? continuation()->node() : node();
2378 bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2380 LayoutPoint adjustedLocation(accumulatedOffset + location());
2381 LayoutSize localOffset = toLayoutSize(adjustedLocation);
2383 if (!isRenderView()) {
2384 // Check if we need to do anything at all.
2385 // If we have clipping, then we can't have any spillout.
2386 LayoutRect overflowBox = hasOverflowClip() ? borderBoxRect() : visualOverflowRect();
2387 flipForWritingMode(overflowBox);
2388 overflowBox.moveBy(adjustedLocation);
2389 if (!locationInContainer.intersects(overflowBox))
2393 if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground)
2394 && visibleToHitTestRequest(request)
2395 && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
2396 updateHitTestResult(result, locationInContainer.point() - localOffset);
2397 // FIXME: isPointInOverflowControl() doesn't handle rect-based tests yet.
2398 if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer))
2402 if (style()->clipPath()) {
2403 switch (style()->clipPath()->type()) {
2404 case ClipPathOperation::SHAPE: {
2405 ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style()->clipPath());
2406 // FIXME: handle marginBox etc.
2407 if (!clipPath->path(borderBoxRect()).contains(locationInContainer.point() - localOffset, clipPath->windRule()))
2411 case ClipPathOperation::REFERENCE:
2412 // FIXME: handle REFERENCE
2417 // If we have clipping, then we can't have any spillout.
2418 bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
2419 bool useClip = (hasControlClip() || useOverflowClip);
2420 bool checkChildren = !useClip;
2421 if (!checkChildren) {
2422 if (hasControlClip()) {
2423 checkChildren = locationInContainer.intersects(controlClipRect(adjustedLocation));
2425 LayoutRect clipRect = overflowClipRect(adjustedLocation, IncludeOverlayScrollbarSize);
2426 if (style()->hasBorderRadius())
2427 checkChildren = locationInContainer.intersects(style()->getRoundedBorderFor(clipRect));
2429 checkChildren = locationInContainer.intersects(clipRect);
2432 if (checkChildren) {
2433 // Hit test descendants first.
2434 LayoutSize scrolledOffset(localOffset);
2435 if (hasOverflowClip())
2436 scrolledOffset -= scrolledContentOffset();
2438 // Hit test contents if we don't have columns.
2439 if (!hasColumns()) {
2440 if (hitTestContents(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
2441 updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2444 if (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, toLayoutPoint(scrolledOffset)))
2446 } else if (hitTestColumns(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
2447 updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2452 // Check if the point is outside radii.
2453 if (style()->hasBorderRadius()) {
2454 LayoutRect borderRect = borderBoxRect();
2455 borderRect.moveBy(adjustedLocation);
2456 RoundedRect border = style()->getRoundedBorderFor(borderRect);
2457 if (!locationInContainer.intersects(border))
2461 // Now hit test our background
2462 if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
2463 LayoutRect boundsRect(adjustedLocation, size());
2464 if (visibleToHitTestRequest(request) && locationInContainer.intersects(boundsRect)) {
2465 updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
2466 if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer, boundsRect))
2474 class ColumnRectIterator {
2475 WTF_MAKE_NONCOPYABLE(ColumnRectIterator);
2477 ColumnRectIterator(const RenderBlock& block)
2479 , m_colInfo(block.columnInfo())
2480 , m_direction(m_block.style()->slowIsFlippedBlocksWritingMode() ? 1 : -1)
2481 , m_isHorizontal(block.isHorizontalWritingMode())
2482 , m_logicalLeft(block.logicalLeftOffsetForContent())
2484 int colCount = m_colInfo->columnCount();
2485 m_colIndex = colCount - 1;
2486 m_currLogicalTopOffset = colCount * m_colInfo->columnHeight() * m_direction;
2497 LayoutRect columnRect() const { return m_colRect; }
2498 bool hasMore() const { return m_colIndex >= 0; }
2500 void adjust(LayoutSize& offset) const
2502 LayoutUnit currLogicalLeftOffset = (m_isHorizontal ? m_colRect.x() : m_colRect.y()) - m_logicalLeft;
2503 offset += m_isHorizontal ? LayoutSize(currLogicalLeftOffset, m_currLogicalTopOffset) : LayoutSize(m_currLogicalTopOffset, currLogicalLeftOffset);
2504 if (m_colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
2506 offset.expand(0, m_colRect.y() - m_block.borderTop() - m_block.paddingTop());
2508 offset.expand(m_colRect.x() - m_block.borderLeft() - m_block.paddingLeft(), 0);
2518 m_colRect = m_block.columnRectAt(const_cast<ColumnInfo*>(m_colInfo), m_colIndex);
2519 m_block.flipForWritingMode(m_colRect);
2520 m_currLogicalTopOffset -= (m_isHorizontal ? m_colRect.height() : m_colRect.width()) * m_direction;
2523 const RenderBlock& m_block;
2524 const ColumnInfo* const m_colInfo;
2525 const int m_direction;
2526 const bool m_isHorizontal;
2527 const LayoutUnit m_logicalLeft;
2529 LayoutUnit m_currLogicalTopOffset;
2530 LayoutRect m_colRect;
2533 bool RenderBlock::hitTestColumns(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2535 // We need to do multiple passes, breaking up our hit testing into strips.
2539 for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
2540 LayoutRect hitRect = locationInContainer.boundingBox();
2541 LayoutRect colRect = it.columnRect();
2542 colRect.moveBy(accumulatedOffset);
2543 if (locationInContainer.intersects(colRect)) {
2544 // The point is inside this column.
2545 // Adjust accumulatedOffset to change where we hit test.
2548 LayoutPoint finalLocation = accumulatedOffset + offset;
2549 if (!result.isRectBasedTest() || colRect.contains(hitRect))
2550 return hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction) || (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, finalLocation));
2552 hitTestContents(request, result, locationInContainer, finalLocation, hitTestAction);
2559 void RenderBlock::adjustForColumnRect(LayoutSize& offset, const LayoutPoint& locationInContainer) const
2561 for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
2562 LayoutRect colRect = it.columnRect();
2563 if (colRect.contains(locationInContainer)) {
2570 bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
2572 if (childrenInline() && !isTable()) {
2573 // We have to hit-test our line boxes.
2574 if (m_lineBoxes.hitTest(this, request, result, locationInContainer, accumulatedOffset, hitTestAction))
2577 // Hit test our children.
2578 HitTestAction childHitTest = hitTestAction;
2579 if (hitTestAction == HitTestChildBlockBackgrounds)
2580 childHitTest = HitTestChildBlockBackground;
2581 for (RenderBox* child = lastChildBox(); child; child = child->previousSiblingBox()) {
2582 LayoutPoint childPoint = flipForWritingModeForChild(child, accumulatedOffset);
2583 if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, locationInContainer, childPoint, childHitTest))
2591 Position RenderBlock::positionForBox(InlineBox *box, bool start) const
2596 if (!box->renderer().nonPseudoNode())
2597 return createLegacyEditingPosition(nonPseudoNode(), start ? caretMinOffset() : caretMaxOffset());
2599 if (!box->isInlineTextBox())
2600 return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? box->renderer().caretMinOffset() : box->renderer().caretMaxOffset());
2602 InlineTextBox* textBox = toInlineTextBox(box);
2603 return createLegacyEditingPosition(box->renderer().nonPseudoNode(), start ? textBox->start() : textBox->start() + textBox->len());
2606 static inline bool isEditingBoundary(RenderObject* ancestor, RenderObject* child)
2608 ASSERT(!ancestor || ancestor->nonPseudoNode());
2609 ASSERT(child && child->nonPseudoNode());
2610 return !ancestor || !ancestor->parent() || (ancestor->hasLayer() && ancestor->parent()->isRenderView())
2611 || ancestor->nonPseudoNode()->hasEditableStyle() == child->nonPseudoNode()->hasEditableStyle();
2614 // FIXME: This function should go on RenderObject as an instance method. Then
2615 // all cases in which positionForPoint recurs could call this instead to
2616 // prevent crossing editable boundaries. This would require many tests.
2617 static PositionWithAffinity positionForPointRespectingEditingBoundaries(RenderBlock* parent, RenderBox* child, const LayoutPoint& pointInParentCoordinates)
2619 LayoutPoint childLocation = child->location();
2620 if (child->isRelPositioned())
2621 childLocation += child->offsetForInFlowPosition();
2623 // FIXME: This is wrong if the child's writing-mode is different from the parent's.
2624 LayoutPoint pointInChildCoordinates(toLayoutPoint(pointInParentCoordinates - childLocation));
2626 // If this is an anonymous renderer, we just recur normally
2627 Node* childNode = child->nonPseudoNode();
2629 return child->positionForPoint(pointInChildCoordinates);
2631 // Otherwise, first make sure that the editability of the parent and child agree.
2632 // If they don't agree, then we return a visible position just before or after the child
2633 RenderObject* ancestor = parent;
2634 while (ancestor && !ancestor->nonPseudoNode())
2635 ancestor = ancestor->parent();
2637 // If we can't find an ancestor to check editability on, or editability is unchanged, we recur like normal
2638 if (isEditingBoundary(ancestor, child))
2639 return child->positionForPoint(pointInChildCoordinates);
2641 // Otherwise return before or after the child, depending on if the click was to the logical left or logical right of the child
2642 LayoutUnit childMiddle = parent->logicalWidthForChild(child) / 2;
2643 LayoutUnit logicalLeft = parent->isHorizontalWritingMode() ? pointInChildCoordinates.x() : pointInChildCoordinates.y();
2644 if (logicalLeft < childMiddle)
2645 return ancestor->createPositionWithAffinity(childNode->nodeIndex(), DOWNSTREAM);
2646 return ancestor->createPositionWithAffinity(childNode->nodeIndex() + 1, UPSTREAM);
2649 PositionWithAffinity RenderBlock::positionForPointWithInlineChildren(const LayoutPoint& pointInLogicalContents)
2651 ASSERT(childrenInline());
2653 if (!firstRootBox())
2654 return createPositionWithAffinity(0, DOWNSTREAM);
2656 bool linesAreFlipped = style()->isFlippedLinesWritingMode();
2657 bool blocksAreFlipped = style()->slowIsFlippedBlocksWritingMode();
2659 // look for the closest line box in the root box which is at the passed-in y coordinate
2660 InlineBox* closestBox = 0;
2661 RootInlineBox* firstRootBoxWithChildren = 0;
2662 RootInlineBox* lastRootBoxWithChildren = 0;
2663 for (RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox()) {
2664 if (!root->firstLeafChild())
2666 if (!firstRootBoxWithChildren)
2667 firstRootBoxWithChildren = root;
2669 if (!linesAreFlipped && root->isFirstAfterPageBreak() && (pointInLogicalContents.y() < root->lineTopWithLeading()
2670 || (blocksAreFlipped && pointInLogicalContents.y() == root->lineTopWithLeading())))
2673 lastRootBoxWithChildren = root;
2675 // check if this root line box is located at this y coordinate
2676 if (pointInLogicalContents.y() < root->selectionBottom() || (blocksAreFlipped && pointInLogicalContents.y() == root->selectionBottom())) {
2677 if (linesAreFlipped) {
2678 RootInlineBox* nextRootBoxWithChildren = root->nextRootBox();
2679 while (nextRootBoxWithChildren && !nextRootBoxWithChildren->firstLeafChild())
2680 nextRootBoxWithChildren = nextRootBoxWithChildren->nextRootBox();
2682 if (nextRootBoxWithChildren && nextRootBoxWithChildren->isFirstAfterPageBreak() && (pointInLogicalContents.y() > nextRootBoxWithChildren->lineTopWithLeading()
2683 || (!blocksAreFlipped && pointInLogicalContents.y() == nextRootBoxWithChildren->lineTopWithLeading())))
2686 closestBox = root->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
2692 bool moveCaretToBoundary = document().frame()->editor().behavior().shouldMoveCaretToHorizontalBoundaryWhenPastTopOrBottom();
2694 if (!moveCaretToBoundary && !closestBox && lastRootBoxWithChildren) {
2695 // y coordinate is below last root line box, pretend we hit it
2696 closestBox = lastRootBoxWithChildren->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
2700 if (moveCaretToBoundary) {
2701 LayoutUnit firstRootBoxWithChildrenTop = std::min<LayoutUnit>(firstRootBoxWithChildren->selectionTop(), firstRootBoxWithChildren->logicalTop());
2702 if (pointInLogicalContents.y() < firstRootBoxWithChildrenTop
2703 || (blocksAreFlipped && pointInLogicalContents.y() == firstRootBoxWithChildrenTop)) {
2704 InlineBox* box = firstRootBoxWithChildren->firstLeafChild();
2705 if (box->isLineBreak()) {
2706 if (InlineBox* newBox = box->nextLeafChildIgnoringLineBreak())
2709 // y coordinate is above first root line box, so return the start of the first
2710 return PositionWithAffinity(positionForBox(box, true), DOWNSTREAM);
2714 // pass the box a top position that is inside it
2715 LayoutPoint point(pointInLogicalContents.x(), closestBox->root().blockDirectionPointInLine());
2716 if (!isHorizontalWritingMode())
2717 point = point.transposedPoint();
2718 if (closestBox->renderer().isReplaced())
2719 return positionForPointRespectingEditingBoundaries(this, &toRenderBox(closestBox->renderer()), point);
2720 return closestBox->renderer().positionForPoint(point);
2723 if (lastRootBoxWithChildren) {
2724 // We hit this case for Mac behavior when the Y coordinate is below the last box.
2725 ASSERT(moveCaretToBoundary);
2726 InlineBox* logicallyLastBox;
2727 if (lastRootBoxWithChildren->getLogicalEndBoxWithNode(logicallyLastBox))
2728 return PositionWithAffinity(positionForBox(logicallyLastBox, false), DOWNSTREAM);
2731 // Can't reach this. We have a root line box, but it has no kids.
2732 // FIXME: This should ASSERT_NOT_REACHED(), but clicking on placeholder text
2733 // seems to hit this code path.
2734 return createPositionWithAffinity(0, DOWNSTREAM);
2737 static inline bool isChildHitTestCandidate(RenderBox* box)
2739 return box->height() && box->style()->visibility() == VISIBLE && !box->isFloatingOrOutOfFlowPositioned();
2742 PositionWithAffinity RenderBlock::positionForPoint(const LayoutPoint& point)
2745 return RenderBox::positionForPoint(point);
2748 // FIXME: This seems wrong when the object's writing-mode doesn't match the line's writing-mode.
2749 LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
2750 LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
2752 if (pointLogicalLeft < 0)
2753 return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2754 if (pointLogicalLeft >= logicalWidth())
2755 return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
2756 if (pointLogicalTop < 0)
2757 return createPositionWithAffinity(caretMinOffset(), DOWNSTREAM);
2758 if (pointLogicalTop >= logicalHeight())
2759 return createPositionWithAffinity(caretMaxOffset(), DOWNSTREAM);
2762 LayoutPoint pointInContents = point;
2763 offsetForContents(pointInContents);
2764 LayoutPoint pointInLogicalContents(pointInContents);
2765 if (!isHorizontalWritingMode())
2766 pointInLogicalContents = pointInLogicalContents.transposedPoint();
2768 if (childrenInline())
2769 return positionForPointWithInlineChildren(pointInLogicalContents);
2771 RenderBox* lastCandidateBox = lastChildBox();
2772 while (lastCandidateBox && !isChildHitTestCandidate(lastCandidateBox))
2773 lastCandidateBox = lastCandidateBox->previousSiblingBox();
2775 bool blocksAreFlipped = style()->slowIsFlippedBlocksWritingMode();
2776 if (lastCandidateBox) {
2777 if (pointInLogicalContents.y() > logicalTopForChild(lastCandidateBox)
2778 || (!blocksAreFlipped && pointInLogicalContents.y() == logicalTopForChild(lastCandidateBox)))
2779 return positionForPointRespectingEditingBoundaries(this, lastCandidateBox, pointInContents);
2781 for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
2782 if (!isChildHitTestCandidate(childBox))
2784 LayoutUnit childLogicalBottom = logicalTopForChild(childBox) + logicalHeightForChild(childBox);
2785 // We hit child if our click is above the bottom of its padding box (like IE6/7 and FF3).
2786 if (isChildHitTestCandidate(childBox) && (pointInLogicalContents.y() < childLogicalBottom
2787 || (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
2788 return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
2792 // We only get here if there are no hit test candidate children below the click.
2793 return RenderBox::positionForPoint(point);
2796 void RenderBlock::offsetForContents(LayoutPoint& offset) const
2798 offset = flipForWritingMode(offset);
2800 if (hasOverflowClip())
2801 offset += scrolledContentOffset();
2804 adjustPointToColumnContents(offset);
2806 offset = flipForWritingMode(offset);
2809 LayoutUnit RenderBlock::availableLogicalWidth() const
2811 // If we have multiple columns, then the available logical width is reduced to our column width.
2813 return desiredColumnWidth();
2814 return RenderBox::availableLogicalWidth();
2817 int RenderBlock::columnGap() const
2819 if (style()->hasNormalColumnGap())
2820 return style()->fontDescription().computedPixelSize(); // "1em" is recommended as the normal gap setting. Matches <p> margins.
2821 return static_cast<int>(style()->columnGap());
2824 void RenderBlock::calcColumnWidth()
2826 if (document().regionBasedColumnsEnabled())
2829 // Calculate our column width and column count.
2830 // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
2831 unsigned desiredColumnCount = 1;
2832 LayoutUnit desiredColumnWidth = contentLogicalWidth();
2834 // For now, we don't support multi-column layouts when printing, since we have to do a lot of work for proper pagination.
2835 if (document().paginated() || !style()->specifiesColumns()) {
2836 setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
2840 LayoutUnit availWidth = desiredColumnWidth;
2841 LayoutUnit colGap = columnGap();
2842 LayoutUnit colWidth = std::max<LayoutUnit>(1, LayoutUnit(style()->columnWidth()));
2843 int colCount = std::max<int>(1, style()->columnCount());
2845 if (style()->hasAutoColumnWidth() && !style()->hasAutoColumnCount()) {
2846 desiredColumnCount = colCount;
2847 desiredColumnWidth = std::max<LayoutUnit>(0, (availWidth - ((desiredColumnCount - 1) * colGap)) / desiredColumnCount);
2848 } else if (!style()->hasAutoColumnWidth() && style()->hasAutoColumnCount()) {
2849 desiredColumnCount = std::max<LayoutUnit>(1, (availWidth + colGap) / (colWidth + colGap));
2850 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
2852 desiredColumnCount = std::max<LayoutUnit>(std::min<LayoutUnit>(colCount, (availWidth + colGap) / (colWidth + colGap)), 1);
2853 desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
2855 setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
2858 bool RenderBlock::requiresColumns(int desiredColumnCount) const
2860 // Paged overflow is treated as multicol here, unless this element was the one that got its
2861 // overflow propagated to the viewport.
2862 bool isPaginated = style()->isOverflowPaged() && node() != document().viewportDefiningElement();
2865 && (desiredColumnCount != 1 || !style()->hasAutoColumnWidth() || isPaginated)
2866 && !firstChild()->isAnonymousColumnsBlock()
2867 && !firstChild()->isAnonymousColumnSpanBlock() && !isFlexibleBoxIncludingDeprecated();
2870 void RenderBlock::setDesiredColumnCountAndWidth(int count, LayoutUnit width)
2872 bool destroyColumns = !requiresColumns(count);
2873 if (destroyColumns) {
2875 gColumnInfoMap->take(this);
2876 setHasColumns(false);
2881 info = gColumnInfoMap->get(this);
2883 if (!gColumnInfoMap)
2884 gColumnInfoMap = new ColumnInfoMap;
2885 info = new ColumnInfo;
2886 gColumnInfoMap->add(this, adoptPtr(info));
2887 setHasColumns(true);
2889 info->setDesiredColumnWidth(width);
2890 if (style()->isOverflowPaged()) {
2891 info->setDesiredColumnCount(1);
2892 info->setProgressionAxis(style()->hasInlinePaginationAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
2894 info->setDesiredColumnCount(count);
2895 info->setProgressionAxis(ColumnInfo::InlineAxis);
2900 LayoutUnit RenderBlock::desiredColumnWidth() const
2903 return contentLogicalWidth();
2904 return gColumnInfoMap->get(this)->desiredColumnWidth();
2907 ColumnInfo* RenderBlock::columnInfo() const
2911 return gColumnInfoMap->get(this);
2914 unsigned RenderBlock::columnCount(ColumnInfo* colInfo) const
2916 ASSERT(hasColumns());
2917 ASSERT(gColumnInfoMap->get(this) == colInfo);
2918 return colInfo->columnCount();
2921 LayoutRect RenderBlock::columnRectAt(ColumnInfo* colInfo, unsigned index) const
2923 ASSERT(hasColumns() && gColumnInfoMap->get(this) == colInfo);
2925 // Compute the appropriate rect based off our information.
2926 LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
2927 LayoutUnit colLogicalHeight = colInfo->columnHeight();
2928 LayoutUnit colLogicalTop = borderBefore() + paddingBefore();
2929 LayoutUnit colLogicalLeft = logicalLeftOffsetForContent();
2930 LayoutUnit colGap = columnGap();
2931 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2932 if (style()->isLeftToRightDirection())
2933 colLogicalLeft += index * (colLogicalWidth + colGap);
2935 colLogicalLeft += contentLogicalWidth() - colLogicalWidth - index * (colLogicalWidth + colGap);
2937 colLogicalTop += index * (colLogicalHeight + colGap);
2940 if (isHorizontalWritingMode())
2941 return LayoutRect(colLogicalLeft, colLogicalTop, colLogicalWidth, colLogicalHeight);
2942 return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
2945 void RenderBlock::adjustPointToColumnContents(LayoutPoint& point) const
2947 // Just bail if we have no columns.
2951 ColumnInfo* colInfo = columnInfo();
2952 if (!columnCount(colInfo))
2955 // Determine which columns we intersect.
2956 LayoutUnit colGap = columnGap();
2957 LayoutUnit halfColGap = colGap / 2;
2958 LayoutPoint columnPoint(columnRectAt(colInfo, 0).location());
2959 LayoutUnit logicalOffset = 0;
2960 for (unsigned i = 0; i < colInfo->columnCount(); i++) {
2961 // Add in half the column gap to the left and right of the rect.
2962 LayoutRect colRect = columnRectAt(colInfo, i);
2963 flipForWritingMode(colRect);
2964 if (isHorizontalWritingMode() == (colInfo->progressionAxis() == ColumnInfo::InlineAxis)) {
2965 LayoutRect gapAndColumnRect(colRect.x() - halfColGap, colRect.y(), colRect.width() + colGap, colRect.height());
2966 if (point.x() >= gapAndColumnRect.x() && point.x() < gapAndColumnRect.maxX()) {
2967 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
2968 // FIXME: The clamping that follows is not completely right for right-to-left
2970 // Clamp everything above the column to its top left.
2971 if (point.y() < gapAndColumnRect.y())
2972 point = gapAndColumnRect.location();
2973 // Clamp everything below the column to the next column's top left. If there is
2974 // no next column, this still maps to just after this column.
2975 else if (point.y() >= gapAndColumnRect.maxY()) {
2976 point = gapAndColumnRect.location();
2977 point.move(0, gapAndColumnRect.height());
2980 if (point.x() < colRect.x())
2981 point.setX(colRect.x());
2982 else if (point.x() >= colRect.maxX())
2983 point.setX(colRect.maxX() - 1);
2986 // We're inside the column. Translate the x and y into our column coordinate space.
2987 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
2988 point.move(columnPoint.x() - colRect.x(), (!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset));
2990 point.move((!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.x() + borderLeft() + paddingLeft(), 0);
2994 // Move to the next position.
2995 logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.height() : colRect.width();
2997 LayoutRect gapAndColumnRect(colRect.x(), colRect.y() - halfColGap, colRect.width(), colRect.height() + colGap);
2998 if (point.y() >= gapAndColumnRect.y() && point.y() < gapAndColumnRect.maxY()) {
2999 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3000 // FIXME: The clamping that follows is not completely right for right-to-left
3002 // Clamp everything above the column to its top left.
3003 if (point.x() < gapAndColumnRect.x())
3004 point = gapAndColumnRect.location();
3005 // Clamp everything below the column to the next column's top left. If there is
3006 // no next column, this still maps to just after this column.
3007 else if (point.x() >= gapAndColumnRect.maxX()) {
3008 point = gapAndColumnRect.location();
3009 point.move(gapAndColumnRect.width(), 0);
3012 if (point.y() < colRect.y())
3013 point.setY(colRect.y());
3014 else if (point.y() >= colRect.maxY())
3015 point.setY(colRect.maxY() - 1);
3018 // We're inside the column. Translate the x and y into our column coordinate space.
3019 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3020 point.move((!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset), columnPoint.y() - colRect.y());
3022 point.move(0, (!style()->slowIsFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.y() + borderTop() + paddingTop());
3026 // Move to the next position.
3027 logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.width() : colRect.height();
3032 void RenderBlock::adjustRectForColumns(LayoutRect& r) const
3034 // Just bail if we have no columns.
3038 ColumnInfo* colInfo = columnInfo();
3040 // Determine which columns we intersect.
3041 unsigned colCount = columnCount(colInfo);
3045 // Begin with a result rect that is empty.
3048 bool isHorizontal = isHorizontalWritingMode();
3049 LayoutUnit beforeBorderPadding = borderBefore() + paddingBefore();
3050 LayoutUnit colHeight = colInfo->columnHeight();
3054 LayoutUnit startOffset = std::max(isHorizontal ? r.y() : r.x(), beforeBorderPadding);
3055 LayoutUnit endOffset = std::max(std::min<LayoutUnit>(isHorizontal ? r.maxY() : r.maxX(), beforeBorderPadding + colCount * colHeight), beforeBorderPadding);
3057 // FIXME: Can overflow on fast/block/float/float-not-removed-from-next-sibling4.html, see https://bugs.webkit.org/show_bug.cgi?id=68744
3058 unsigned startColumn = (startOffset - beforeBorderPadding) / colHeight;
3059 unsigned endColumn = (endOffset - beforeBorderPadding) / colHeight;
3061 if (startColumn == endColumn) {
3062 // The rect is fully contained within one column. Adjust for our offsets
3063 // and issue paint invalidations only that portion.
3064 LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent();
3065 LayoutRect colRect = columnRectAt(colInfo, startColumn);
3066 LayoutRect paintInvalidationRect = r;
3068 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
3070 paintInvalidationRect.move(colRect.x() - logicalLeftOffset, - static_cast<int>(startColumn) * colHeight);
3072 paintInvalidationRect.move(- static_cast<int>(startColumn) * colHeight, colRect.y() - logicalLeftOffset);
3075 paintInvalidationRect.move(0, colRect.y() - startColumn * colHeight - beforeBorderPadding);
3077 paintInvalidationRect.move(colRect.x() - startColumn * colHeight - beforeBorderPadding, 0);
3079 paintInvalidationRect.intersect(colRect);
3080 result.unite(paintInvalidationRect);
3082 // We span multiple columns. We can just unite the start and end column to get the final
3083 // paint invalidation rect.
3084 result.unite(columnRectAt(colInfo, startColumn));
3085 result.unite(columnRectAt(colInfo, endColumn));
3091 LayoutPoint RenderBlock::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
3093 ASSERT(hasColumns());
3094 if (!hasColumns() || !style()->slowIsFlippedBlocksWritingMode())
3096 ColumnInfo* colInfo = columnInfo();
3097 LayoutUnit columnLogicalHeight = colInfo->columnHeight();
3098 LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
3099 if (isHorizontalWritingMode())
3100 return LayoutPoint(point.x(), expandedLogicalHeight - point.y());
3101 return LayoutPoint(expandedLogicalHeight - point.x(), point.y());
3104 void RenderBlock::adjustStartEdgeForWritingModeIncludingColumns(LayoutRect& rect) const
3106 ASSERT(hasColumns());
3107 if (!hasColumns() || !style()->slowIsFlippedBlocksWritingMode())
3110 ColumnInfo* colInfo = columnInfo();
3111 LayoutUnit columnLogicalHeight = colInfo->columnHeight();
3112 LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
3114 if (isHorizontalWritingMode())
3115 rect.setY(expandedLogicalHeight - rect.maxY());
3117 rect.setX(expandedLogicalHeight - rect.maxX());
3120 LayoutSize RenderBlock::columnOffset(const LayoutPoint& point) const
3123 return LayoutSize();
3125 ColumnInfo* colInfo = columnInfo();
3127 LayoutUnit logicalLeft = logicalLeftOffsetForContent();
3128 unsigned colCount = columnCount(colInfo);
3129 LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
3130 LayoutUnit colLogicalHeight = colInfo->columnHeight();
3132 for (unsigned i = 0; i < colCount; ++i) {
3133 // Compute the edges for a given column in the block progression direction.
3134 LayoutRect sliceRect = LayoutRect(logicalLeft, borderBefore() + paddingBefore() + i * colLogicalHeight, colLogicalWidth, colLogicalHeight);
3135 if (!isHorizontalWritingMode())
3136 sliceRect = sliceRect.transposedRect();
3138 LayoutUnit logicalOffset = i * colLogicalHeight;
3140 // Now we're in the same coordinate space as the point. See if it is inside the rectangle.
3141 if (isHorizontalWritingMode()) {
3142 if (point.y() >= sliceRect.y() && point.y() < sliceRect.maxY()) {
3143 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3144 return LayoutSize(columnRectAt(colInfo, i).x() - logicalLeft, -logicalOffset);
3145 return LayoutSize(0, columnRectAt(colInfo, i).y() - logicalOffset - borderBefore() - paddingBefore());
3148 if (point.x() >= sliceRect.x() && point.x() < sliceRect.maxX()) {
3149 if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
3150 return LayoutSize(-logicalOffset, columnRectAt(colInfo, i).y() - logicalLeft);
3151 return LayoutSize(columnRectAt(colInfo, i).x() - logicalOffset - borderBefore() - paddingBefore(), 0);
3156 return LayoutSize();
3159 void RenderBlock::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3161 if (childrenInline()) {
3162 // FIXME: Remove this const_cast.
3163 toRenderBlockFlow(const_cast<RenderBlock*>(this))->computeInlinePreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
3165 computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
3168 maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
3170 adjustIntrinsicLogicalWidthsForColumns(minLogicalWidth, maxLogicalWidth);
3172 if (isTableCell()) {
3173 Length tableCellWidth = toRenderTableCell(this)->styleOrColLogicalWidth();
3174 if (tableCellWidth.isFixed() && tableCellWidth.value() > 0)
3175 maxLogicalWidth = std::max(minLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(tableCellWidth.value()));
3178 int scrollbarWidth = instrinsicScrollbarLogicalWidth();
3179 maxLogicalWidth += scrollbarWidth;
3180 minLogicalWidth += scrollbarWidth;
3183 void RenderBlock::computePreferredLogicalWidths()
3185 ASSERT(preferredLogicalWidthsDirty());
3187 updateFirstLetter();
3189 m_minPreferredLogicalWidth = 0;
3190 m_maxPreferredLogicalWidth = 0;
3192 // FIXME: The isFixed() calls here should probably be checking for isSpecified since you
3193 // should be able to use percentage, calc or viewport relative values for width.
3194 RenderStyle* styleToUse = style();
3195 if (!isTableCell() && styleToUse->logicalWidth().isFixed() && styleToUse->logicalWidth().value() >= 0
3196 && !(isDeprecatedFlexItem() && !styleToUse->logicalWidth().intValue()))
3197 m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalWidth().value());
3199 computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
3201 if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
3202 m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
3203 m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMinWidth().value()));
3206 if (styleToUse->logicalMaxWidth().isFixed()) {
3207 m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
3208 m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse->logicalMaxWidth().value()));
3211 // Table layout uses integers, ceil the preferred widths to ensure that they can contain the contents.
3212 if (isTableCell()) {
3213 m_minPreferredLogicalWidth = m_minPreferredLogicalWidth.ceil();
3214 m_maxPreferredLogicalWidth = m_maxPreferredLogicalWidth.ceil();
3217 LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
3218 m_minPreferredLogicalWidth += borderAndPadding;
3219 m_maxPreferredLogicalWidth += borderAndPadding;
3221 clearPreferredLogicalWidthsDirty();
3224 void RenderBlock::adjustIntrinsicLogicalWidthsForColumns(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3226 if (!style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth()) {
3227 // The min/max intrinsic widths calculated really tell how much space elements need when
3228 // laid out inside the columns. In order to eventually end up with the desired column width,
3229 // we need to convert them to values pertaining to the multicol container.
3230 int columnCount = style()->hasAutoColumnCount() ? 1 : style()->columnCount();
3231 LayoutUnit columnWidth;
3232 LayoutUnit gapExtra = (columnCount - 1) * columnGap();
3233 if (style()->hasAutoColumnWidth()) {
3234 minLogicalWidth = minLogicalWidth * columnCount + gapExtra;
3236 columnWidth = style()->columnWidth();
3237 minLogicalWidth = std::min(minLogicalWidth, columnWidth);
3239 // FIXME: If column-count is auto here, we should resolve it to calculate the maximum
3240 // intrinsic width, instead of pretending that it's 1. The only way to do that is by
3241 // performing a layout pass, but this is not an appropriate time or place for layout. The
3242 // good news is that if height is unconstrained and there are no explicit breaks, the
3243 // resolved column-count really should be 1.
3244 maxLogicalWidth = std::max(maxLogicalWidth, columnWidth) * columnCount + gapExtra;
3248 void RenderBlock::computeBlockPreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
3250 RenderStyle* styleToUse = style();
3251 bool nowrap = styleToUse->whiteSpace() == NOWRAP;
3253 RenderObject* child = firstChild();
3254 RenderBlock* containingBlock = this->containingBlock();
3255 LayoutUnit floatLeftWidth = 0, floatRightWidth = 0;
3257 // Positioned children don't affect the min/max width
3258 if (child->isOutOfFlowPositioned()) {
3259 child = child->nextSibling();
3263 RefPtr<RenderStyle> childStyle = child->style();
3264 if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
3265 LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
3266 if (childStyle->clear() & CLEFT) {
3267 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3270 if (childStyle->clear() & CRIGHT) {
3271 maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
3272 floatRightWidth = 0;
3276 // A margin basically has three types: fixed, percentage, and auto (variable).
3277 // Auto and percentage margins simply become 0 when computing min/max width.
3278 // Fixed margins can be added in as is.
3279 Length startMarginLength = childStyle->marginStartUsing(styleToUse);
3280 Length endMarginLength = childStyle->marginEndUsing(styleToUse);
3281 LayoutUnit margin = 0;
3282 LayoutUnit marginStart = 0;
3283 LayoutUnit marginEnd = 0;
3284 if (startMarginLength.isFixed())
3285 marginStart += startMarginLength.value();
3286 if (endMarginLength.isFixed())
3287 marginEnd += endMarginLength.value();
3288 margin = marginStart + marginEnd;
3290 LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
3291 if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
3292 RenderBox* childBox = toRenderBox(child);
3293 LogicalExtentComputedValues computedValues;
3294 childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
3295 childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
3297 childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
3298 childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
3301 LayoutUnit w = childMinPreferredLogicalWidth + margin;
3302 minLogicalWidth = std::max(w, minLogicalWidth);
3304 // IE ignores tables for calculation of nowrap. Makes some sense.
3305 if (nowrap && !child->isTable())
3306 maxLogicalWidth = std::max(w, maxLogicalWidth);
3308 w = childMaxPreferredLogicalWidth + margin;
3310 if (!child->isFloating()) {
3311 if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
3312 // Determine a left and right max value based off whether or not the floats can fit in the
3313 // margins of the object. For negative margins, we will attempt to overlap the float if the negative margin
3314 // is smaller than the float width.
3315 bool ltr = containingBlock ? containingBlock->style()->isLeftToRightDirection() : styleToUse->isLeftToRightDirection();
3316 LayoutUnit marginLogicalLeft = ltr ? marginStart : marginEnd;
3317 LayoutUnit marginLogicalRight = ltr ? marginEnd : marginStart;
3318 LayoutUnit maxLeft = marginLogicalLeft > 0 ? std::max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
3319 LayoutUnit maxRight = marginLogicalRight > 0 ? std::max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
3320 w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
3321 w = std::max(w, floatLeftWidth + floatRightWidth);
3323 maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3325 floatLeftWidth = floatRightWidth = 0;
3328 if (child->isFloating()) {
3329 if (childStyle->floating() == LeftFloat)
3330 floatLeftWidth += w;
3332 floatRightWidth += w;
3334 maxLogicalWidth = std::max(w, maxLogicalWidth);
3337 child = child->nextSibling();
3340 // Always make sure these values are non-negative.
3341 minLogicalWidth = std::max<LayoutUnit>(0, minLogicalWidth);
3342 maxLogicalWidth = std::max<LayoutUnit>(0, maxLogicalWidth);
3344 maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
3347 bool RenderBlock::hasLineIfEmpty() const
3352 if (node()->isRootEditableElement())
3355 if (node()->isShadowRoot() && isHTMLInputElement(*toShadowRoot(node())->host()))
3361 LayoutUnit RenderBlock::lineHeight(bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3363 // Inline blocks are replaced elements. Otherwise, just pass off to
3364 // the base class. If we're being queried as though we're the root line
3365 // box, then the fact that we're an inline-block is irrelevant, and we behave
3366 // just like a block.
3367 if (isReplaced() && linePositionMode == PositionOnContainingLine)
3368 return RenderBox::lineHeight(firstLine, direction, linePositionMode);
3370 RenderStyle* s = style(firstLine && document().styleEngine()->usesFirstLineRules());
3371 return s->computedLineHeight();
3374 int RenderBlock::beforeMarginInLineDirection(LineDirectionMode direction) const
3376 return direction == HorizontalLine ? marginTop() : marginRight();
3379 int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
3381 // Inline blocks are replaced elements. Otherwise, just pass off to
3382 // the base class. If we're being queried as though we're the root line
3383 // box, then the fact that we're an inline-block is irrelevant, and we behave
3384 // just like a block.
3385 if (isInline() && linePositionMode == PositionOnContainingLine) {
3386 // For "leaf" theme objects, let the theme decide what the baseline position is.
3387 // FIXME: Might be better to have a custom CSS property instead, so that if the theme
3388 // is turned off, checkboxes/radios will still have decent baselines.
3389 // FIXME: Need to patch form controls to deal with vertical lines.
3390 if (style()->hasAppearance() && !RenderTheme::theme().isControlContainer(style()->appearance()))
3391 return RenderTheme::theme().baselinePosition(this);
3393 // CSS2.1 states that the baseline of an inline block is the baseline of the last line box in
3395 // We give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
3396 // vertically (e.g., an overflow:hidden block that has had scrollTop moved).
3397 bool ignoreBaseline = (layer() && layer()->scrollableArea()
3398 && (direction == HorizontalLine
3399 ? (layer()->scrollableArea()->verticalScrollbar() || layer()->scrollableArea()->scrollYOffset())
3400 : (layer()->scrollableArea()->horizontalScrollbar() || layer()->scrollableArea()->scrollXOffset())))
3401 || (isWritingModeRoot() && !isRubyRun());
3403 int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
3405 if (isDeprecatedFlexibleBox()) {
3406 // Historically, we did this check for all baselines. But we can't
3407 // remove this code from deprecated flexbox, because it effectively
3408 // breaks -webkit-line-clamp, which is used in the wild -- we would
3409 // calculate the baseline as if -webkit-line-clamp wasn't used.
3410 // For simplicity, we use this for all uses of deprecated flexbox.
3411 LayoutUnit bottomOfContent = direction == HorizontalLine ? borderTop() + paddingTop() + contentHeight() : borderRight() + paddingRight() + contentWidth();
3412 if (baselinePos > bottomOfContent)
3415 if (baselinePos != -1)
3416 return beforeMarginInLineDirection(direction) + baselinePos;
3418 return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
3421 // If we're not replaced, we'll only get called with PositionOfInteriorLineBoxes.
3422 // Note that inline-block counts as replaced here.
3423 ASSERT(linePositionMode == PositionOfInteriorLineBoxes);
3425 const FontMetrics& fontMetrics = style(firstLine)->fontMetrics();
3426 return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
3429 LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
3431 if (!document().inNoQuirksMode() && replacedHeight)
3432 return replacedHeight;
3434 if (!(style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
3437 return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
3440 int RenderBlock::firstLineBoxBaseline() const
3442 if (isWritingModeRoot() && !isRubyRun())
3445 if (childrenInline()) {
3447 return firstLineBox()->logicalTop() + style(true)->fontMetrics().ascent(firstRootBox()->baselineType());
3452 for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
3453 if (!curr->isFloatingOrOutOfFlowPositioned()) {
3454 int result = curr->firstLineBoxBaseline();
3456 return curr->logicalTop() + result; // Translate to our coordinate space.
3464 int RenderBlock::inlineBlockBaseline(LineDirectionMode direction) const
3466 if (!style()->isOverflowVisible()) {
3467 // We are not calling RenderBox::baselinePosition here because the caller should add the margin-top/margin-right, not us.
3468 return direction == HorizontalLine ? height() + m_marginBox.bottom() : width() + m_marginBox.left();
3471 return lastLineBoxBaseline(direction);
3474 int RenderBlock::lastLineBoxBaseline(LineDirectionMode lineDirection) const
3476 if (isWritingModeRoot() && !isRubyRun())
3479 if (childrenInline()) {
3480 if (!firstLineBox() && hasLineIfEmpty()) {
3481 const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
3482 return fontMetrics.ascent()
3483 + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3484 + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3487 return lastLineBox()->logicalTop() + style(lastLineBox() == firstLineBox())->fontMetrics().ascent(lastRootBox()->baselineType());
3490 bool haveNormalFlowChild = false;
3491 for (RenderBox* curr = lastChildBox(); curr; curr = curr->previousSiblingBox()) {
3492 if (!curr->isFloatingOrOutOfFlowPositioned()) {
3493 haveNormalFlowChild = true;
3494 int result = curr->inlineBlockBaseline(lineDirection);
3496 return curr->logicalTop() + result; // Translate to our coordinate space.
3499 if (!haveNormalFlowChild && hasLineIfEmpty()) {
3500 const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
3501 return fontMetrics.ascent()
3502 + (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
3503 + (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
3510 static inline bool isRenderBlockFlowOrRenderButton(RenderObject* renderObject)
3512 // We include isRenderButton in this check because buttons are implemented
3513 // using flex box but should still support first-line|first-letter.
3514 // The flex box and grid specs require that flex box and grid do not
3515 // support first-line|first-letter, though.
3516 // FIXME: Remove when buttons are implemented with align-items instead
3518 return renderObject->isRenderBlockFlow() || renderObject->isRenderButton();
3521 RenderBlock* RenderBlock::firstLineBlock() const
3523 RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
3524 bool hasPseudo = false;
3526 hasPseudo = firstLineBlock->style()->hasPseudoStyle(FIRST_LINE);
3529 RenderObject* parentBlock = firstLineBlock->parent();
3530 if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
3532 || !isRenderBlockFlowOrRenderButton(parentBlock))
3534 ASSERT_WITH_SECURITY_IMPLICATION(parentBlock->isRenderBlock());
3535 if (toRenderBlock(parentBlock)->firstChild() != firstLineBlock)
3537 firstLineBlock = toRenderBlock(parentBlock);
3543 return firstLineBlock;
3546 static RenderStyle* styleForFirstLetter(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer)
3548 RenderStyle* pseudoStyle = firstLetterBlock->getCachedPseudoStyle(FIRST_LETTER, firstLetterContainer->firstLineStyle());
3549 // Force inline display (except for floating first-letters).
3550 pseudoStyle->setDisplay(pseudoStyle->isFloating() ? BLOCK : INLINE);
3551 // CSS2 says first-letter can't be positioned.
3552 pseudoStyle->setPosition(StaticPosition);
3556 // CSS 2.1 http://www.w3.org/TR/CSS21/selector.html#first-letter
3557 // "Punctuation (i.e, characters defined in Unicode [UNICODE] in the "open" (Ps), "close" (Pe),
3558 // "initial" (Pi). "final" (Pf) and "other" (Po) punctuation classes), that precedes or follows the first letter should be included"
3559 static inline bool isPunctuationForFirstLetter(UChar c)
3561 CharCategory charCategory = category(c);
3562 return charCategory == Punctuation_Open
3563 || charCategory == Punctuation_Close
3564 || charCategory == Punctuation_InitialQuote
3565 || charCategory == Punctuation_FinalQuote
3566 || charCategory == Punctuation_Other;
3569 static inline bool isSpaceForFirstLetter(UChar c)
3571 return isSpaceOrNewline(c) || c == noBreakSpace;
3574 static inline RenderObject* findFirstLetterBlock(RenderBlock* start)
3576 RenderObject* firstLetterBlock = start;
3578 bool canHaveFirstLetterRenderer = firstLetterBlock->style()->hasPseudoStyle(FIRST_LETTER)
3579 && firstLetterBlock->canHaveGeneratedChildren()
3580 && isRenderBlockFlowOrRenderButton(firstLetterBlock);
3581 if (canHaveFirstLetterRenderer)
3582 return firstLetterBlock;
3584 RenderObject* parentBlock = firstLetterBlock->parent();
3585 if (firstLetterBlock->isReplaced() || !parentBlock
3586 || !isRenderBlockFlowOrRenderButton(parentBlock)) {
3589 ASSERT(parentBlock->isRenderBlock());
3590 if (toRenderBlock(parentBlock)->firstChild() != firstLetterBlock)
3592 firstLetterBlock = parentBlock;
3598 void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
3600 RenderObject* firstLetter = currentChild->parent();
3601 RenderObject* firstLetterContainer = firstLetter->parent();
3602 RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3603 ASSERT(firstLetter->isFloating() || firstLetter->isInline());
3605 if (RenderStyle::stylePropagationDiff(firstLetter->style(), pseudoStyle) == Reattach) {
3606 // The first-letter renderer needs to be replaced. Create a new renderer of the right type.
3607 RenderBoxModelObject* newFirstLetter;
3608 if (pseudoStyle->display() == INLINE)
3609 newFirstLetter = RenderInline::createAnonymous(&document());
3611 newFirstLetter = RenderBlockFlow::createAnonymous(&document());
3612 newFirstLetter->setStyle(pseudoStyle);
3614 // Move the first letter into the new renderer.
3615 while (RenderObject* child = firstLetter->slowFirstChild()) {
3616 if (child->isText())
3617 toRenderText(child)->removeAndDestroyTextBoxes();
3618 firstLetter->removeChild(child);
3619 newFirstLetter->addChild(child, 0);
3622 RenderObject* nextSibling = firstLetter->nextSibling();
3623 if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
3624 ASSERT(remainingText->isAnonymous() || remainingText->node()->renderer() == remainingText);
3625 // Replace the old renderer with the new one.
3626 remainingText->setFirstLetter(newFirstLetter);
3627 newFirstLetter->setFirstLetterRemainingText(remainingText);
3629 // To prevent removal of single anonymous block in RenderBlock::removeChild and causing
3630 // |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
3631 firstLetterContainer->virtualChildren()->removeChildNode(firstLetterContainer, firstLetter);
3632 firstLetter->destroy();
3633 firstLetter = newFirstLetter;
3634 firstLetterContainer->addChild(firstLetter, nextSibling);
3636 firstLetter->setStyle(pseudoStyle);
3639 for (RenderObject* genChild = firstLetter->slowFirstChild(); genChild; genChild = genChild->nextSibling()) {
3640 if (genChild->isText())
3641 genChild->setStyle(pseudoStyle);
3645 static inline unsigned firstLetterLength(const String& text)
3647 unsigned length = 0;
3648 unsigned textLength = text.length();
3650 if (textLength == 0)
3653 // Account for leading spaces first.
3654 while (length < textLength && isSpaceForFirstLetter(text[length]))
3657 // Now account for leading punctuation.
3658 while (length < textLength && isPunctuationForFirstLetter(text[length]))
3661 // Bail if we didn't find a letter before the end of the text or before a space.
3662 if (isSpaceForFirstLetter(text[length]) || length == textLength)
3665 // Account the next character for first letter.
3668 // Keep looking allowed punctuation for the :first-letter.
3669 for (unsigned scanLength = length; scanLength < textLength; ++scanLength) {
3670 UChar c = text[scanLength];
3672 if (!isPunctuationForFirstLetter(c))
3675 length = scanLength + 1;
3680 void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderText& currentChild, unsigned length)
3684 RenderObject* firstLetterContainer = currentChild.parent();
3685 RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
3686 RenderBoxModelObject* firstLetter = 0;
3687 if (pseudoStyle->display() == INLINE)
3688 firstLetter = RenderInline::createAnonymous(&document());
3690 firstLetter = RenderBlockFlow::createAnonymous(&document());
3691 firstLetter->setStyle(pseudoStyle);
3693 // FIXME: The first letter code should not modify the render tree during
3694 // layout. crbug.com/370458
3695 DeprecatedDisableModifyRenderTreeStructureAsserts disabler;
3697 firstLetterContainer->addChild(firstLetter, ¤tChild);
3699 // The original string is going to be either a generated content string or a DOM node's
3700 // string. We want the original string before it got transformed in case first-letter has
3701 // no text-transform or a different text-transform applied to it.
3702 String oldText = currentChild.originalText();
3703 ASSERT(oldText.impl());
3705 // Construct a text fragment for the text after the first letter.
3706 // This text fragment might be empty.
3707 RenderTextFragment* remainingText =
3708 new RenderTextFragment(currentChild.node() ? currentChild.node() : ¤tChild.document(), oldText.impl(), length, oldText.length() - length);
3709 remainingText->setStyle(currentChild.style());
3710 if (remainingText->node())
3711 remainingText->node()->setRenderer(remainingText);
3713 firstLetterContainer->addChild(remainingText, ¤tChild);
3714 firstLetterContainer->removeChild(¤tChild);
3715 remainingText->setFirstLetter(firstLetter);
3716 firstLetter->setFirstLetterRemainingText(remainingText);
3718 // construct text fragment for the first letter
3719 RenderTextFragment* letter =
3720 new RenderTextFragment(remainingText->node() ? remainingText->node() : &remainingText->document(), oldText.impl(), 0, length);
3721 letter->setStyle(pseudoStyle);
3722 firstLetter->addChild(letter);
3724 currentChild.destroy();
3727 // Once we see any of these renderers we can stop looking for first-letter as
3728 // they signal the end of the first line of text.
3729 bool RenderBlock::isInvalidFirstLetterRenderer(RenderObject* obj) const
3731 return (obj->isBR() || (obj->isText() && toRenderText(obj)->isWordBreak()));
3734 void RenderBlock::updateFirstLetter()
3736 if (!document().styleEngine()->usesFirstLetterRules())
3739 if (style()->styleType() == FIRST_LETTER)
3742 // FIXME: We need to destroy the first-letter object if it is no longer the first child. Need to find
3743 // an efficient way to check for that situation though before implementing anything.
3744 RenderObject* firstLetterBlock = findFirstLetterBlock(this);
3745 if (!firstLetterBlock)
3748 // Drill into inlines looking for our first text child.
3749 RenderObject* currChild = firstLetterBlock->slowFirstChild();
3750 unsigned length = 0;
3752 if (currChild->isText()) {
3753 // FIXME: If there is leading punctuation in a different RenderText than
3754 // the first letter, we'll not apply the correct style to it.
3755 length = firstLetterLength(toRenderText(currChild)->originalText());
3756 if (length || isInvalidFirstLetterRenderer(currChild))
3758 currChild = currChild->nextSibling();
3759 } else if (currChild->isListMarker()) {
3760 currChild = currChild->nextSibling();
3761 } else if (currChild->isFloatingOrOutOfFlowPositioned()) {
3762 if (currChild->style()->styleType() == FIRST_LETTER) {
3763 currChild = currChild->slowFirstChild();
3766 currChild = currChild->nextSibling();
3767 } else if (currChild->isReplaced() || currChild->isRenderButton() || currChild->isMenuList()) {
3769 } else if (currChild->isFlexibleBoxIncludingDeprecated() || currChild->isRenderGrid()) {
3771 } else if (currChild->style()->hasPseudoStyle(FIRST_LETTER) && currChild->canHaveGeneratedChildren()) {
3772 // We found a lower-level node with first-letter, which supersedes the higher-level style
3773 firstLetterBlock = currChild;
3774 currChild = currChild->slowFirstChild();
3776 currChild = currChild->slowFirstChild();
3783 // If the child already has style, then it has already been created, so we just want
3785 if (currChild->parent()->style()->styleType() == FIRST_LETTER) {
3786 updateFirstLetterStyle(firstLetterBlock, currChild);
3790 // FIXME: This black-list of disallowed RenderText subclasses is fragile.
3791 // Should counter be on this list? What about RenderTextFragment?
3792 if (!currChild->isText() || isInvalidFirstLetterRenderer(currChild))
3795 createFirstLetterRenderer(firstLetterBlock, toRenderText(*currChild), length);
3798 // Helper methods for obtaining the last line, computing line counts and heights for line counts
3799 // (crawling into blocks).
3800 static bool shouldCheckLines(RenderObject* obj)
3802 return !obj->isFloatingOrOutOfFlowPositioned()
3803 && obj->isRenderBlock() && obj->style()->height().isAuto()
3804 && (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
3807 static int getHeightForLineCount(RenderBlock* block, int l, bool includeBottom, int& count)
3809 if (block->style()->visibility() == VISIBLE) {
3810 if (block->isRenderBlockFlow() && block->childrenInline()) {
3811 for (RootInlineBox* box = toRenderBlockFlow(block)->firstRootBox(); box; box = box->nextRootBox()) {
3813 return box->lineBottom() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : LayoutUnit());
3816 RenderBox* normalFlowChildWithoutLines = 0;
3817 for (RenderBox* obj = block->firstChildBox(); obj; obj = obj->nextSiblingBox()) {
3818 if (shouldCheckLines(obj)) {
3819 int result = getHeightForLineCount(toRenderBlock(obj), l, false, count);
3821 return result + obj->y() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : LayoutUnit());
3822 } else if (!obj->isFloatingOrOutOfFlowPositioned()) {
3823 normalFlowChildWithoutLines = obj;
3826 if (normalFlowChildWithoutLines && l == 0)
3827 return normalFlowChildWithoutLines->y() + normalFlowChildWithoutLines->height();
3834 RootInlineBox* RenderBlock::lineAtIndex(int i) const
3838 if (style()->visibility() != VISIBLE)
3841 if (childrenInline()) {
3842 for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
3846 for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
3847 if (!shouldCheckLines(child))
3849 if (RootInlineBox* box = toRenderBlock(child)->lineAtIndex(i))
3857 int RenderBlock::lineCount(const RootInlineBox* stopRootInlineBox, bool* found) const
3861 if (style()->visibility() == VISIBLE) {
3862 if (childrenInline())
3863 for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) {
3865 if (box == stopRootInlineBox) {
3872 for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling())
3873 if (shouldCheckLines(obj)) {
3874 bool recursiveFound = false;
3875 count += toRenderBlock(obj)->lineCount(stopRootInlineBox, &recursiveFound);
3876 if (recursiveFound) {
3886 int RenderBlock::heightForLineCount(int l)
3889 return getHeightForLineCount(this, l, true, count);
3892 void RenderBlock::clearTruncation()
3894 if (style()->visibility() == VISIBLE) {
3895 if (childrenInline() && hasMarkupTruncation()) {
3896 setHasMarkupTruncation(false);
3897 for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
3898 box->clearTruncation();
3900 for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling()) {
3901 if (shouldCheckLines(obj))
3902 toRenderBlock(obj)->clearTruncation();
3908 void RenderBlock::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
3910 // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3911 // inline boxes above and below us (thus getting merged with them to form a single irregular
3913 if (isAnonymousBlockContinuation()) {
3914 // FIXME: This is wrong for block-flows that are horizontal.
3915 // https://bugs.webkit.org/show_bug.cgi?id=46781
3916 rects.append(pixelSnappedIntRect(accumulatedOffset.x(), accumulatedOffset.y() - collapsedMarginBefore(),
3917 width(), height() + collapsedMarginBefore() + collapsedMarginAfter()));
3918 continuation()->absoluteRects(rects, accumulatedOffset - toLayoutSize(location() +
3919 inlineElementContinuation()->containingBlock()->location()));
3921 rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
3924 void RenderBlock::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
3926 // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3927 // inline boxes above and below us (thus getting merged with them to form a single irregular
3929 if (isAnonymousBlockContinuation()) {
3930 // FIXME: This is wrong for block-flows that are horizontal.
3931 // https://bugs.webkit.org/show_bug.cgi?id=46781
3932 FloatRect localRect(0, -collapsedMarginBefore().toFloat(),
3933 width().toFloat(), (height() + collapsedMarginBefore() + collapsedMarginAfter()).toFloat());
3934 quads.append(localToAbsoluteQuad(localRect, 0 /* mode */, wasFixed));
3935 continuation()->absoluteQuads(quads, wasFixed);
3937 quads.append(RenderBox::localToAbsoluteQuad(FloatRect(0, 0, width().toFloat(), height().toFloat()), 0 /* mode */, wasFixed));
3941 LayoutRect RenderBlock::rectWithOutlineForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, LayoutUnit outlineWidth, const PaintInvalidationState* paintInvalidationState) const
3943 LayoutRect r(RenderBox::rectWithOutlineForPaintInvalidation(paintInvalidationContainer, outlineWidth, paintInvalidationState));
3944 if (isAnonymousBlockContinuation())
3945 r.inflateY(collapsedMarginBefore()); // FIXME: This is wrong for block-flows that are horizontal.
3949 RenderObject* RenderBlock::hoverAncestor() const
3951 return isAnonymousBlockContinuation() ? continuation() : RenderBox::hoverAncestor();
3954 void RenderBlock::updateDragState(bool dragOn)
3956 RenderBox::updateDragState(dragOn);
3958 continuation()->updateDragState(dragOn);
3961 void RenderBlock::childBecameNonInline(RenderObject*)
3963 makeChildrenNonInline();
3964 if (isAnonymousBlock() && parent() && parent()->isRenderBlock())
3965 toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
3966 // |this| may be dead here
3969 void RenderBlock::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
3971 if (result.innerNode())
3974 if (Node* n = nodeForHitTest()) {
3975 result.setInnerNode(n);
3976 if (!result.innerNonSharedNode())
3977 result.setInnerNonSharedNode(n);
3978 result.setLocalPoint(point);
3982 LayoutRect RenderBlock::localCaretRect(InlineBox* inlineBox, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
3984 // Do the normal calculation in most cases.
3986 return RenderBox::localCaretRect(inlineBox, caretOffset, extraWidthToEndOfLine);
3988 LayoutRect caretRect = localCaretRectForEmptyElement(width(), textIndentOffset());
3990 if (extraWidthToEndOfLine)
3991 *extraWidthToEndOfLine = width() - caretRect.maxX();
3996 void RenderBlock::addFocusRingRects(Vector<LayoutRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer) const
3998 // For blocks inside inlines, we go ahead and include margins so that we run right up to the
3999 // inline boxes above and below us (thus getting merged with them to form a single irregular
4001 if (inlineElementContinuation()) {
4002 // FIXME: This check really isn't accurate.
4003 bool nextInlineHasLineBox = inlineElementContinuation()->firstLineBox();
4004 // FIXME: This is wrong. The principal renderer may not be the continuation preceding this block.
4005 // FIXME: This is wrong for block-flows that are horizontal.
4006 // https://bugs.webkit.org/show_bug.cgi?id=46781
4007 bool prevInlineHasLineBox = toRenderInline(inlineElementContinuation()->node()->renderer())->firstLineBox();
4008 LayoutUnit topMargin = prevInlineHasLineBox ? collapsedMarginBefore() : LayoutUnit();
4009 LayoutUnit bottomMargin = nextInlineHasLineBox ? collapsedMarginAfter() : LayoutUnit();
4010 LayoutRect rect(additionalOffset.x(), additionalOffset.y() - topMargin, width(), height() + topMargin + bottomMargin);
4011 if (!rect.isEmpty())
4013 } else if (width() && height()) {
4014 rects.append(LayoutRect(additionalOffset, size()));
4017 if (!hasOverflowClip() && !hasControlClip()) {
4018 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
4019 LayoutUnit top = std::max<LayoutUnit>(curr->lineTop(), curr->top());
4020 LayoutUnit bottom = std::min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
4021 LayoutRect rect(additionalOffset.x() + curr->x(), additionalOffset.y() + top, curr->width(), bottom - top);
4022 if (!rect.isEmpty())
4026 addChildFocusRingRects(rects, additionalOffset, paintContainer);
4029 if (inlineElementContinuation())
4030 inlineElementContinuation()->addFocusRingRects(rects, additionalOffset + (inlineElementContinuation()->containingBlock()->location() - location()), paintContainer);
4033 void RenderBlock::computeSelfHitTestRects(Vector<LayoutRect>& rects, const LayoutPoint& layerOffset) const
4035 RenderBox::computeSelfHitTestRects(rects, layerOffset);
4037 if (hasHorizontalLayoutOverflow() || hasVerticalLayoutOverflow()) {
4038 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
4039 LayoutUnit top = std::max<LayoutUnit>(curr->lineTop(), curr->top());
4040 LayoutUnit bottom = std::min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
4041 LayoutRect rect(layerOffset.x() + curr->x(), layerOffset.y() + top, curr->width(), bottom - top);
4042 // It's common for this rect to be entirely contained in our box, so exclude that simple case.
4043 if (!rect.isEmpty() && (rects.isEmpty() || !rects[0].contains(rect)))
4049 RenderBox* RenderBlock::createAnonymousBoxWithSameTypeAs(const RenderObject* parent) const
4051 if (isAnonymousColumnsBlock())
4052 return createAnonymousColumnsWithParentRenderer(parent);
4053 if (isAnonymousColumnSpanBlock())
4054 return createAnonymousColumnSpanWithParentRenderer(parent);
4055 return createAnonymousWithParentRendererAndDisplay(parent, style()->display());
4058 LayoutUnit RenderBlock::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
4060 LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
4061 if (!pageLogicalHeight)
4062 return logicalOffset;
4064 // The logicalOffset is in our coordinate space. We can add in our pushed offset.
4065 LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
4066 if (pageBoundaryRule == ExcludePageBoundary)
4067 return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
4068 return logicalOffset + remainingLogicalHeight;
4071 LayoutUnit RenderBlock::pageLogicalHeightForOffset(LayoutUnit offset) const
4073 RenderView* renderView = view();
4074 RenderFlowThread* flowThread = flowThreadContainingBlock();
4076 return renderView->layoutState()->pageLogicalHeight();
4077 return flowThread->pageLogicalHeightForOffset(offset + offsetFromLogicalTopOfFirstPage());
4080 LayoutUnit RenderBlock::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
4082 RenderView* renderView = view();
4083 offset += offsetFromLogicalTopOfFirstPage();
4085 RenderFlowThread* flowThread = flowThreadContainingBlock();
4087 LayoutUnit pageLogicalHeight = renderView->layoutState()->pageLogicalHeight();
4088 LayoutUnit remainingHeight = pageLogicalHeight - intMod(offset, pageLogicalHeight);
4089 if (pageBoundaryRule == IncludePageBoundary) {
4090 // If includeBoundaryPoint is true the line exactly on the top edge of a
4091 // column will act as being part of the previous column.
4092 remainingHeight = intMod(remainingHeight, pageLogicalHeight);
4094 return remainingHeight;
4097 return flowThread->pageRemainingLogicalHeightForOffset(offset, pageBoundaryRule);
4100 void RenderBlock::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
4102 if (RenderFlowThread* flowThread = flowThreadContainingBlock())
4103 flowThread->setPageBreak(offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
4106 void RenderBlock::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
4108 if (RenderFlowThread* flowThread = flowThreadContainingBlock())
4109 flowThread->updateMinimumPageHeight(offsetFromLogicalTopOfFirstPage() + offset, minHeight);
4110 else if (ColumnInfo* colInfo = view()->layoutState()->columnInfo())
4111 colInfo->updateMinimumColumnHeight(minHeight);
4114 LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
4116 LayoutState* layoutState = view()->layoutState();
4117 if (layoutState && !layoutState->isPaginated())
4120 RenderFlowThread* flowThread = flowThreadContainingBlock();
4122 return flowThread->offsetFromLogicalTopOfFirstRegion(this);
4125 ASSERT(layoutState->renderer() == this);
4127 LayoutSize offsetDelta = layoutState->layoutOffset() - layoutState->pageOffset();
4128 return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
4131 ASSERT_NOT_REACHED();
4135 LayoutUnit RenderBlock::collapsedMarginBeforeForChild(const RenderBox* child) const
4137 // If the child has the same directionality as we do, then we can just return its
4138 // collapsed margin.
4139 if (!child->isWritingModeRoot())
4140 return child->collapsedMarginBefore();
4142 // The child has a different directionality. If the child is parallel, then it's just
4143 // flipped relative to us. We can use the collapsed margin for the opposite edge.
4144 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4145 return child->collapsedMarginAfter();
4147 // The child is perpendicular to us, which means its margins don't collapse but are on the
4148 // "logical left/right" sides of the child box. We can just return the raw margin in this case.
4149 return marginBeforeForChild(child);
4152 LayoutUnit RenderBlock::collapsedMarginAfterForChild(const RenderBox* child) const
4154 // If the child has the same directionality as we do, then we can just return its
4155 // collapsed margin.
4156 if (!child->isWritingModeRoot())
4157 return child->collapsedMarginAfter();
4159 // The child has a different directionality. If the child is parallel, then it's just
4160 // flipped relative to us. We can use the collapsed margin for the opposite edge.
4161 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4162 return child->collapsedMarginBefore();
4164 // The child is perpendicular to us, which means its margins don't collapse but are on the
4165 // "logical left/right" side of the child box. We can just return the raw margin in this case.
4166 return marginAfterForChild(child);
4169 bool RenderBlock::hasMarginBeforeQuirk(const RenderBox* child) const
4171 // If the child has the same directionality as we do, then we can just return its
4173 if (!child->isWritingModeRoot())
4174 return child->isRenderBlock() ? toRenderBlock(child)->hasMarginBeforeQuirk() : child->style()->hasMarginBeforeQuirk();
4176 // The child has a different directionality. If the child is parallel, then it's just
4177 // flipped relative to us. We can use the opposite edge.
4178 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4179 return child->isRenderBlock() ? toRenderBlock(child)->hasMarginAfterQuirk() : child->style()->hasMarginAfterQuirk();
4181 // The child is perpendicular to us and box sides are never quirky in html.css, and we don't really care about
4182 // whether or not authors specified quirky ems, since they're an implementation detail.
4186 bool RenderBlock::hasMarginAfterQuirk(const RenderBox* child) const
4188 // If the child has the same directionality as we do, then we can just return its
4190 if (!child->isWritingModeRoot())
4191 return child->isRenderBlock() ? toRenderBlock(child)->hasMarginAfterQuirk() : child->style()->hasMarginAfterQuirk();
4193 // The child has a different directionality. If the child is parallel, then it's just
4194 // flipped relative to us. We can use the opposite edge.
4195 if (child->isHorizontalWritingMode() == isHorizontalWritingMode())
4196 return child->isRenderBlock() ? toRenderBlock(child)->hasMarginBeforeQuirk() : child->style()->hasMarginBeforeQuirk();
4198 // The child is perpendicular to us and box sides are never quirky in html.css, and we don't really care about
4199 // whether or not authors specified quirky ems, since they're an implementation detail.
4203 const char* RenderBlock::renderName() const
4206 return "RenderBody"; // FIXME: Temporary hack until we know that the regression tests pass.
4208 return "RenderBlock (floating)";
4209 if (isOutOfFlowPositioned())
4210 return "RenderBlock (positioned)";
4212 if (isAnonymousColumnsBlock())
4213 return "RenderBlock (anonymous multi-column)";
4214 if (isAnonymousColumnSpanBlock())
4215 return "RenderBlock (anonymous multi-column span)";
4216 if (isAnonymousBlock())
4217 return "RenderBlock (anonymous)";
4220 return "RenderBlock (generated)";
4221 if (isRelPositioned())
4222 return "RenderBlock (relative positioned)";
4223 return "RenderBlock";
4226 RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const RenderObject* parent, EDisplay display)
4228 // FIXME: Do we need to convert all our inline displays to block-type in the anonymous logic ?
4229 EDisplay newDisplay;
4230 RenderBlock* newBox = 0;
4231 if (display == FLEX || display == INLINE_FLEX) {
4232 newBox = RenderFlexibleBox::createAnonymous(&parent->document());
4235 newBox = RenderBlockFlow::createAnonymous(&parent->document());
4239 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), newDisplay);
4240 parent->updateAnonymousChildStyle(newBox, newStyle.get());
4241 newBox->setStyle(newStyle.release());
4245 RenderBlockFlow* RenderBlock::createAnonymousColumnsWithParentRenderer(const RenderObject* parent)
4247 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
4248 newStyle->inheritColumnPropertiesFrom(parent->style());
4250 RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
4251 parent->updateAnonymousChildStyle(newBox, newStyle.get());
4252 newBox->setStyle(newStyle.release());
4256 RenderBlockFlow* RenderBlock::createAnonymousColumnSpanWithParentRenderer(const RenderObject* parent)
4258 RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
4259 newStyle->setColumnSpan(ColumnSpanAll);
4261 RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
4262 parent->updateAnonymousChildStyle(newBox, newStyle.get());
4263 newBox->setStyle(newStyle.release());
4267 static bool recalcNormalFlowChildOverflowIfNeeded(RenderObject* renderer)
4269 if (renderer->isOutOfFlowPositioned() || !renderer->needsOverflowRecalcAfterStyleChange())
4272 ASSERT(renderer->isRenderBlock());
4273 return toRenderBlock(renderer)->recalcOverflowAfterStyleChange();
4276 bool RenderBlock::recalcChildOverflowAfterStyleChange()
4278 ASSERT(childNeedsOverflowRecalcAfterStyleChange());
4279 setChildNeedsOverflowRecalcAfterStyleChange(false);
4281 bool childrenOverflowChanged = false;
4283 if (childrenInline()) {
4284 ListHashSet<RootInlineBox*> lineBoxes;
4285 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
4286 RenderObject* renderer = walker.current();
4287 if (recalcNormalFlowChildOverflowIfNeeded(renderer)) {
4288 childrenOverflowChanged = true;
4289 if (InlineBox* inlineBoxWrapper = toRenderBlock(renderer)->inlineBoxWrapper())
4290 lineBoxes.add(&inlineBoxWrapper->root());
4294 // FIXME: Glyph overflow will get lost in this case, but not really a big deal.
4295 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
4296 for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
4297 RootInlineBox* box = *it;
4298 box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
4301 for (RenderBox* box = firstChildBox(); box; box = box->nextSiblingBox()) {
4302 if (recalcNormalFlowChildOverflowIfNeeded(box))
4303 childrenOverflowChanged = true;
4307 TrackedRendererListHashSet* positionedDescendants = positionedObjects();
4308 if (!positionedDescendants)
4309 return childrenOverflowChanged;
4311 TrackedRendererListHashSet::iterator end = positionedDescendants->end();
4312 for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
4313 RenderBox* box = *it;
4315 if (!box->needsOverflowRecalcAfterStyleChange())
4317 RenderBlock* block = toRenderBlock(box);
4318 if (!block->recalcOverflowAfterStyleChange() || box->style()->position() == FixedPosition)
4321 childrenOverflowChanged = true;
4323 return childrenOverflowChanged;
4326 bool RenderBlock::recalcOverflowAfterStyleChange()
4328 ASSERT(needsOverflowRecalcAfterStyleChange());
4330 bool childrenOverflowChanged = false;
4331 if (childNeedsOverflowRecalcAfterStyleChange())
4332 childrenOverflowChanged = recalcChildOverflowAfterStyleChange();
4334 if (!selfNeedsOverflowRecalcAfterStyleChange() && !childrenOverflowChanged)
4337 setSelfNeedsOverflowRecalcAfterStyleChange(false);
4338 // If the current block needs layout, overflow will be recalculated during
4339 // layout time anyway. We can safely exit here.
4343 LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
4344 computeOverflow(oldClientAfterEdge, true);
4346 if (hasOverflowClip())
4347 layer()->scrollableArea()->updateAfterOverflowRecalc();
4349 return !hasOverflowClip();
4353 void RenderBlock::checkPositionedObjectsNeedLayout()
4355 if (!gPositionedDescendantsMap)
4358 if (TrackedRendererListHashSet* positionedDescendantSet = positionedObjects()) {
4359 TrackedRendererListHashSet::const_iterator end = positionedDescendantSet->end();
4360 for (TrackedRendererListHashSet::const_iterator it = positionedDescendantSet->begin(); it != end; ++it) {
4361 RenderBox* currBox = *it;
4362 ASSERT(!currBox->needsLayout());
4367 bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
4369 ContinuationOutlineTableMap* table = continuationOutlineTable();
4370 if (table->isEmpty())
4373 ListHashSet<RenderInline*>* continuations = table->get(this);
4377 return continuations->contains(flow);
4384 void RenderBlock::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj) const
4387 for (const RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox())
4388 root->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, 1);
4393 } // namespace blink