#include "config.h"
#include "RenderBlock.h"
#include "AXObjectCache.h"
#include "Document.h"
#include "Editor.h"
#include "Element.h"
#include "FloatQuad.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLInputElement.h"
#include "HTMLNames.h"
#include "HitTestLocation.h"
#include "HitTestResult.h"
#include "InlineElementBox.h"
#include "InlineIterator.h"
#include "InlineTextBox.h"
#include "LayoutRepainter.h"
#include "LogicalSelectionOffsetCaches.h"
#include "OverflowEvent.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderBlockFlow.h"
#include "RenderBoxRegionInfo.h"
#include "RenderCombineText.h"
#include "RenderDeprecatedFlexibleBox.h"
#include "RenderFlexibleBox.h"
#include "RenderInline.h"
#include "RenderIterator.h"
#include "RenderLayer.h"
#include "RenderNamedFlowFragment.h"
#include "RenderNamedFlowThread.h"
#include "RenderRegion.h"
#include "RenderTableCell.h"
#include "RenderTextFragment.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "SVGTextRunRenderingContext.h"
#include "Settings.h"
#include "ShadowRoot.h"
#include "TransformState.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/StackStats.h>
#include <wtf/TemporaryChange.h>
#if ENABLE(CSS_SHAPES)
#include "ShapeOutsideInfo.h"
#endif
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
struct SameSizeAsRenderBlock : public RenderBox {
uint32_t bitfields;
};
COMPILE_ASSERT(sizeof(RenderBlock) == sizeof(SameSizeAsRenderBlock), RenderBlock_should_stay_small);
static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
static TrackedContainerMap* gPositionedContainerMap = 0;
static TrackedContainerMap* gPercentHeightContainerMap = 0;
typedef HashMap<RenderBlock*, std::unique_ptr<ListHashSet<RenderInline*>>> ContinuationOutlineTableMap;
struct UpdateScrollInfoAfterLayoutTransaction {
UpdateScrollInfoAfterLayoutTransaction(const RenderView& view)
: nestedCount(0)
, view(&view)
{
}
int nestedCount;
const RenderView* view;
HashSet<RenderBlock*> blocks;
};
typedef Vector<UpdateScrollInfoAfterLayoutTransaction> DelayedUpdateScrollInfoStack;
static std::unique_ptr<DelayedUpdateScrollInfoStack>& updateScrollInfoAfterLayoutTransactionStack()
{
static NeverDestroyed<std::unique_ptr<DelayedUpdateScrollInfoStack>> delayedUpdatedScrollInfoStack;
return delayedUpdatedScrollInfoStack;
}
struct RenderBlockRareData {
WTF_MAKE_NONCOPYABLE(RenderBlockRareData); WTF_MAKE_FAST_ALLOCATED;
public:
RenderBlockRareData()
: m_paginationStrut(0)
, m_pageLogicalOffset(0)
{
}
LayoutUnit m_paginationStrut;
LayoutUnit m_pageLogicalOffset;
};
typedef HashMap<const RenderBlock*, std::unique_ptr<RenderBlockRareData>> RenderBlockRareDataMap;
static RenderBlockRareDataMap* gRareDataMap = 0;
class OverflowEventDispatcher {
WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
public:
OverflowEventDispatcher(const RenderBlock* block)
: m_block(block)
, m_hadHorizontalLayoutOverflow(false)
, m_hadVerticalLayoutOverflow(false)
{
m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
if (m_shouldDispatchEvent) {
m_hadHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
m_hadVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
}
}
~OverflowEventDispatcher()
{
if (!m_shouldDispatchEvent)
return;
bool hasHorizontalLayoutOverflow = m_block->hasHorizontalLayoutOverflow();
bool hasVerticalLayoutOverflow = m_block->hasVerticalLayoutOverflow();
bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
return;
RefPtr<OverflowEvent> overflowEvent = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
overflowEvent->setTarget(m_block->element());
m_block->document().enqueueOverflowEvent(overflowEvent.release());
}
private:
const RenderBlock* m_block;
bool m_shouldDispatchEvent;
bool m_hadHorizontalLayoutOverflow;
bool m_hadVerticalLayoutOverflow;
};
RenderBlock::RenderBlock(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags)
: RenderBox(element, WTF::move(style), baseTypeFlags | RenderBlockFlag)
, m_lineHeight(-1)
, m_hasMarginBeforeQuirk(false)
, m_hasMarginAfterQuirk(false)
, m_beingDestroyed(false)
, m_hasMarkupTruncation(false)
, m_hasBorderOrPaddingLogicalWidthChanged(false)
, m_lineLayoutPath(UndeterminedPath)
{
}
RenderBlock::RenderBlock(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags)
: RenderBox(document, WTF::move(style), baseTypeFlags | RenderBlockFlag)
, m_lineHeight(-1)
, m_hasMarginBeforeQuirk(false)
, m_hasMarginAfterQuirk(false)
, m_beingDestroyed(false)
, m_hasMarkupTruncation(false)
, m_hasBorderOrPaddingLogicalWidthChanged(false)
, m_lineLayoutPath(UndeterminedPath)
{
}
static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
{
if (std::unique_ptr<TrackedRendererListHashSet> descendantSet = descendantMap->take(block)) {
TrackedRendererListHashSet::iterator end = descendantSet->end();
for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
TrackedContainerMap::iterator it = containerMap->find(*descendant);
ASSERT(it != containerMap->end());
if (it == containerMap->end())
continue;
HashSet<RenderBlock*>* containerSet = it->value.get();
ASSERT(containerSet->contains(block));
containerSet->remove(block);
if (containerSet->isEmpty())
containerMap->remove(it);
}
}
}
RenderBlock::~RenderBlock()
{
if (gRareDataMap)
gRareDataMap->remove(this);
if (gPercentHeightDescendantsMap)
removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
if (gPositionedDescendantsMap)
removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
}
bool RenderBlock::hasRareData() const
{
return gRareDataMap ? gRareDataMap->contains(this) : false;
}
void RenderBlock::willBeDestroyed()
{
m_beingDestroyed = true;
destroyLeftoverChildren();
RenderBoxModelObject* continuation = this->continuation();
if (continuation) {
continuation->destroy();
setContinuation(0);
}
if (!documentBeingDestroyed()) {
if (parent())
parent()->dirtyLinesFromChangedChild(this);
}
removeFromUpdateScrollInfoAfterLayoutTransaction();
RenderBox::willBeDestroyed();
}
void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle& newStyle)
{
const RenderStyle* oldStyle = hasInitializedStyle() ? &style() : nullptr;
setReplaced(newStyle.isDisplayInlineType());
if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle.position()) {
if (newStyle.position() == StaticPosition)
removePositionedObjects(0, NewContainingBlock);
else if (oldStyle->position() == StaticPosition) {
auto cb = parent();
while (cb && (cb->style().position() == StaticPosition || (cb->isInline() && !cb->isReplaced())) && !cb->isRenderView()) {
if (cb->style().position() == RelativePosition && cb->isInline() && !cb->isReplaced()) {
cb = cb->containingBlock();
break;
}
cb = cb->parent();
}
if (cb->isRenderBlock())
toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
}
}
RenderBox::styleWillChange(diff, newStyle);
}
static bool borderOrPaddingLogicalWidthChanged(const RenderStyle* oldStyle, const RenderStyle* newStyle)
{
if (newStyle->isHorizontalWritingMode())
return oldStyle->borderLeftWidth() != newStyle->borderLeftWidth()
|| oldStyle->borderRightWidth() != newStyle->borderRightWidth()
|| oldStyle->paddingLeft() != newStyle->paddingLeft()
|| oldStyle->paddingRight() != newStyle->paddingRight();
return oldStyle->borderTopWidth() != newStyle->borderTopWidth()
|| oldStyle->borderBottomWidth() != newStyle->borderBottomWidth()
|| oldStyle->paddingTop() != newStyle->paddingTop()
|| oldStyle->paddingBottom() != newStyle->paddingBottom();
}
void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
RenderStyle& newStyle = style();
if (!isAnonymousBlock()) {
for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
RenderBoxModelObject* nextCont = currCont->continuation();
currCont->setContinuation(0);
currCont->setStyle(newStyle);
currCont->setContinuation(nextCont);
}
}
propagateStyleToAnonymousChildren(PropagateToBlockChildrenOnly);
m_lineHeight = -1;
m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, &newStyle);
}
RenderBlock* RenderBlock::continuationBefore(RenderObject* beforeChild)
{
if (beforeChild && beforeChild->parent() == this)
return this;
RenderBlock* curr = toRenderBlock(continuation());
RenderBlock* nextToLast = this;
RenderBlock* last = this;
while (curr) {
if (beforeChild && beforeChild->parent() == curr) {
if (curr->firstChild() == beforeChild)
return last;
return curr;
}
nextToLast = last;
last = curr;
curr = toRenderBlock(curr->continuation());
}
if (!beforeChild && !last->firstChild())
return nextToLast;
return last;
}
void RenderBlock::addChildToContinuation(RenderObject* newChild, RenderObject* beforeChild)
{
RenderBlock* flow = continuationBefore(beforeChild);
ASSERT(!beforeChild || beforeChild->parent()->isRenderBlock());
RenderBoxModelObject* beforeChildParent = 0;
if (beforeChild)
beforeChildParent = toRenderBoxModelObject(beforeChild->parent());
else {
RenderBoxModelObject* cont = flow->continuation();
if (cont)
beforeChildParent = cont;
else
beforeChildParent = flow;
}
if (newChild->isFloatingOrOutOfFlowPositioned()) {
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
bool childIsNormal = newChild->isInline() || !newChild->style().columnSpan();
bool bcpIsNormal = beforeChildParent->isInline() || !beforeChildParent->style().columnSpan();
bool flowIsNormal = flow->isInline() || !flow->style().columnSpan();
if (flow == beforeChildParent) {
flow->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
if (childIsNormal == bcpIsNormal) {
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
return;
}
if (flowIsNormal == childIsNormal) {
flow->addChildIgnoringContinuation(newChild, 0); return;
}
beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
}
RenderPtr<RenderBlock> RenderBlock::clone() const
{
RenderPtr<RenderBlock> cloneBlock;
if (isAnonymousBlock()) {
cloneBlock = RenderPtr<RenderBlock>(createAnonymousBlock());
cloneBlock->setChildrenInline(childrenInline());
} else {
cloneBlock = static_pointer_cast<RenderBlock>(element()->createElementRenderer(style()));
cloneBlock->initializeStyle();
cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
}
cloneBlock->setFlowThreadState(flowThreadState());
return cloneBlock;
}
void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
RenderBlock* middleBlock,
RenderObject* beforeChild, RenderBoxModelObject* oldCont)
{
RenderPtr<RenderBlock> cloneBlock = clone();
if (!isAnonymousBlock())
cloneBlock->setContinuation(oldCont);
if (!beforeChild && isAfterContent(lastChild()))
beforeChild = lastChild();
if (beforeChild && childrenInline())
deleteLines();
moveChildrenTo(cloneBlock.get(), beforeChild, 0, true);
if (!cloneBlock->isAnonymousBlock())
middleBlock->setContinuation(cloneBlock.get());
RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
RenderBoxModelObject* currChild = this;
RenderObject* currChildNextSibling = currChild->nextSibling();
while (curr && curr->isDescendantOf(fromBlock) && curr != fromBlock) {
RenderBlock* blockCurr = toRenderBlock(curr);
RenderPtr<RenderBlock> cloneChild = WTF::move(cloneBlock);
cloneBlock = blockCurr->clone();
cloneBlock->addChildIgnoringContinuation(cloneChild.leakPtr(), 0);
if (!blockCurr->isAnonymousBlock()) {
oldCont = blockCurr->continuation();
blockCurr->setContinuation(cloneBlock.get());
cloneBlock->setContinuation(oldCont);
}
blockCurr->moveChildrenTo(cloneBlock.get(), currChildNextSibling, 0, true);
currChild = curr;
currChildNextSibling = currChild->nextSibling();
curr = toRenderBoxModelObject(curr->parent());
}
toBlock->insertChildInternal(cloneBlock.leakPtr(), nullptr, NotifyChildren);
if (currChildNextSibling && currChildNextSibling->parent() == fromBlock)
fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
}
void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
{
if (continuation() && !isAnonymousBlock())
addChildToContinuation(newChild, beforeChild);
else
addChildIgnoringContinuation(newChild, beforeChild);
}
void RenderBlock::addChildIgnoringContinuation(RenderObject* newChild, RenderObject* beforeChild)
{
if (beforeChild && beforeChild->parent() != this) {
RenderElement* beforeChildContainer = beforeChild->parent();
while (beforeChildContainer->parent() != this)
beforeChildContainer = beforeChildContainer->parent();
ASSERT(beforeChildContainer);
if (beforeChildContainer->isAnonymous()) {
RenderElement* beforeChildAnonymousContainer = beforeChildContainer;
if (beforeChildAnonymousContainer->isAnonymousBlock()
#if ENABLE(FULLSCREEN_API)
|| beforeChildAnonymousContainer->isRenderFullScreen()
|| beforeChildAnonymousContainer->isRenderFullScreenPlaceholder()
#endif
) {
if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
beforeChild->parent()->addChild(newChild, beforeChild);
else
addChild(newChild, beforeChild->parent());
return;
}
ASSERT(beforeChildAnonymousContainer->isTable());
if (newChild->isTablePart()) {
beforeChildAnonymousContainer->addChild(newChild, beforeChild);
return;
}
beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
ASSERT(beforeChild->parent() == this);
if (beforeChild->parent() != this) {
beforeChild = beforeChildContainer;
}
}
}
bool madeBoxesNonInline = false;
if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrOutOfFlowPositioned()) {
makeChildrenNonInline(beforeChild);
madeBoxesNonInline = true;
if (beforeChild && beforeChild->parent() != this) {
beforeChild = beforeChild->parent();
ASSERT(beforeChild->isAnonymousBlock());
ASSERT(beforeChild->parent() == this);
}
} else if (!childrenInline() && (newChild->isFloatingOrOutOfFlowPositioned() || newChild->isInline())) {
RenderObject* afterChild = beforeChild ? beforeChild->previousSibling() : lastChild();
if (afterChild && afterChild->isAnonymousBlock()) {
toRenderBlock(afterChild)->addChild(newChild);
return;
}
if (newChild->isInline()) {
RenderBlock* newBox = createAnonymousBlock();
RenderBox::addChild(newBox, beforeChild);
newBox->addChild(newChild);
return;
}
}
invalidateLineLayoutPath();
RenderBox::addChild(newChild, beforeChild);
if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
}
static void getInlineRun(RenderObject* start, RenderObject* boundary,
RenderObject*& inlineRunStart,
RenderObject*& inlineRunEnd)
{
RenderObject * curr = start;
bool sawInline;
do {
while (curr && !(curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()))
curr = curr->nextSibling();
inlineRunStart = inlineRunEnd = curr;
if (!curr)
return;
sawInline = curr->isInline();
curr = curr->nextSibling();
while (curr && (curr->isInline() || curr->isFloatingOrOutOfFlowPositioned()) && (curr != boundary)) {
inlineRunEnd = curr;
if (curr->isInline())
sawInline = true;
curr = curr->nextSibling();
}
} while (!sawInline);
}
void RenderBlock::deleteLines()
{
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->recomputeIsIgnored(this);
}
void RenderBlock::makeChildrenNonInline(RenderObject* insertionPoint)
{
ASSERT(isInlineBlockOrInlineTable() || !isInline());
ASSERT(!insertionPoint || insertionPoint->parent() == this);
setChildrenInline(false);
RenderObject* child = firstChild();
if (!child)
return;
deleteLines();
while (child) {
RenderObject* inlineRunStart;
RenderObject* inlineRunEnd;
getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
if (!inlineRunStart)
break;
child = inlineRunEnd->nextSibling();
RenderBlock* block = createAnonymousBlock();
insertChildInternal(block, inlineRunStart, NotifyChildren);
moveChildrenTo(block, inlineRunStart, child);
}
#ifndef NDEBUG
for (RenderObject* c = firstChild(); c; c = c->nextSibling())
ASSERT(!c->isInline());
#endif
repaint();
}
void RenderBlock::removeLeftoverAnonymousBlock(RenderBlock* child)
{
ASSERT(child->isAnonymousBlock());
ASSERT(!child->childrenInline());
if (child->continuation())
return;
RenderObject* firstAnChild = child->firstChild();
RenderObject* lastAnChild = child->lastChild();
if (firstAnChild) {
RenderObject* o = firstAnChild;
while (o) {
o->setParent(this);
o = o->nextSibling();
}
firstAnChild->setPreviousSibling(child->previousSibling());
lastAnChild->setNextSibling(child->nextSibling());
if (child->previousSibling())
child->previousSibling()->setNextSibling(firstAnChild);
if (child->nextSibling())
child->nextSibling()->setPreviousSibling(lastAnChild);
if (child == firstChild())
setFirstChild(firstAnChild);
if (child == lastChild())
setLastChild(lastAnChild);
} else {
if (child == firstChild())
setFirstChild(child->nextSibling());
if (child == lastChild())
setLastChild(child->previousSibling());
if (child->previousSibling())
child->previousSibling()->setNextSibling(child->nextSibling());
if (child->nextSibling())
child->nextSibling()->setPreviousSibling(child->previousSibling());
}
child->setFirstChild(0);
child->m_next = 0;
child->removeFromRenderFlowThread();
child->setParent(0);
child->setPreviousSibling(0);
child->setNextSibling(0);
child->destroy();
}
static bool canMergeAnonymousBlock(RenderBlock* anonymousBlock)
{
if (anonymousBlock->beingDestroyed() || anonymousBlock->continuation())
return false;
if (anonymousBlock->isRubyRun() || anonymousBlock->isRubyBase())
return false;
return true;
}
static bool canMergeContiguousAnonymousBlocks(RenderObject& oldChild, RenderObject* previous, RenderObject* next)
{
if (oldChild.documentBeingDestroyed() || oldChild.isInline() || oldChild.virtualContinuation())
return false;
if (previous) {
if (!previous->isAnonymousBlock())
return false;
RenderBlock* previousAnonymousBlock = toRenderBlock(previous);
if (!canMergeAnonymousBlock(previousAnonymousBlock))
return false;
}
if (next) {
if (!next->isAnonymousBlock())
return false;
RenderBlock* nextAnonymousBlock = toRenderBlock(next);
if (!canMergeAnonymousBlock(nextAnonymousBlock))
return false;
}
return true;
}
void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderBlock* child)
{
parent->setNeedsLayoutAndPrefWidthsRecalc();
parent->setChildrenInline(child->childrenInline());
RenderObject* nextSibling = child->nextSibling();
RenderFlowThread* childFlowThread = child->flowThreadContainingBlock();
CurrentRenderFlowThreadMaintainer flowThreadMaintainer(childFlowThread);
if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(child);
parent->removeChildInternal(*child, child->hasLayer() ? NotifyChildren : DontNotifyChildren);
child->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
child->deleteLines();
child->destroy();
}
RenderObject* RenderBlock::removeChild(RenderObject& oldChild)
{
if (documentBeingDestroyed())
return RenderBox::removeChild(oldChild);
RenderObject* prev = oldChild.previousSibling();
RenderObject* next = oldChild.nextSibling();
bool canMergeAnonymousBlocks = canMergeContiguousAnonymousBlocks(oldChild, prev, next);
if (canMergeAnonymousBlocks && prev && next) {
prev->setNeedsLayoutAndPrefWidthsRecalc();
RenderBlock* nextBlock = toRenderBlock(next);
RenderBlock* prevBlock = toRenderBlock(prev);
if (prev->childrenInline() != next->childrenInline()) {
RenderBlock* inlineChildrenBlock = prev->childrenInline() ? prevBlock : nextBlock;
RenderBlock* blockChildrenBlock = prev->childrenInline() ? nextBlock : prevBlock;
ASSERT(!inlineChildrenBlock->continuation());
bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
inlineChildrenBlock->setStyle(RenderStyle::createAnonymousStyleWithDisplay(&style(), BLOCK));
removeChildInternal(*inlineChildrenBlock, inlineChildrenBlockHasLayer ? NotifyChildren : DontNotifyChildren);
RenderObject* beforeChild = prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : nullptr;
blockChildrenBlock->insertChildInternal(inlineChildrenBlock, beforeChild,
(inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer()) ? NotifyChildren : DontNotifyChildren);
next->setNeedsLayoutAndPrefWidthsRecalc();
if (inlineChildrenBlock == prevBlock)
prev = 0;
else
next = 0;
} else {
nextBlock->moveAllChildrenIncludingFloatsTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
nextBlock->deleteLines();
nextBlock->destroy();
next = 0;
}
}
invalidateLineLayoutPath();
RenderObject* nextSibling = RenderBox::removeChild(oldChild);
RenderObject* child = prev ? prev : next;
if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && canCollapseAnonymousBlockChild()) {
collapseAnonymousBoxChild(this, toRenderBlock(child));
nextSibling = nullptr;
} else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && canCollapseAnonymousBlockChild()) {
RenderBlock* anonBlock = toRenderBlock((prev && prev->isAnonymousBlock()) ? prev : next);
if ((anonBlock->previousSibling() || anonBlock->nextSibling())
&& (!anonBlock->previousSibling() || (anonBlock->previousSibling()->style().styleType() != NOPSEUDO && anonBlock->previousSibling()->isFloating() && !anonBlock->previousSibling()->previousSibling()))
&& (!anonBlock->nextSibling() || (anonBlock->nextSibling()->style().styleType() != NOPSEUDO && anonBlock->nextSibling()->isFloating() && !anonBlock->nextSibling()->nextSibling()))) {
collapseAnonymousBoxChild(this, anonBlock);
nextSibling = nullptr;
}
}
if (!firstChild()) {
nextSibling = nullptr;
if (childrenInline())
deleteLines();
if (!beingDestroyed() && isAnonymousBlockContinuation() && !oldChild.isListMarker()) {
auto containingBlockIgnoringAnonymous = containingBlock();
while (containingBlockIgnoringAnonymous && containingBlockIgnoringAnonymous->isAnonymousBlock())
containingBlockIgnoringAnonymous = containingBlockIgnoringAnonymous->containingBlock();
for (RenderObject* curr = this; curr; curr = curr->previousInPreOrder(containingBlockIgnoringAnonymous)) {
if (curr->virtualContinuation() != this)
continue;
RenderBoxModelObject* nextContinuation = continuation();
if (curr->isRenderInline())
toRenderInline(curr)->setContinuation(nextContinuation);
else if (curr->isRenderBlock())
toRenderBlock(curr)->setContinuation(nextContinuation);
else
ASSERT_NOT_REACHED();
break;
}
setContinuation(0);
destroy();
}
}
return nextSibling;
}
bool RenderBlock::isSelfCollapsingBlock() const
{
if (logicalHeight() > 0
|| isTable() || borderAndPaddingLogicalHeight()
|| style().logicalMinHeight().isPositive()
|| style().marginBeforeCollapse() == MSEPARATE || style().marginAfterCollapse() == MSEPARATE)
return false;
Length logicalHeightLength = style().logicalHeight();
bool hasAutoHeight = logicalHeightLength.isAuto();
if (logicalHeightLength.isPercent() && !document().inQuirksMode()) {
hasAutoHeight = true;
for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
if (cb->style().logicalHeight().isFixed() || cb->isTableCell())
hasAutoHeight = false;
}
}
if (hasAutoHeight || ((logicalHeightLength.isFixed() || logicalHeightLength.isPercent()) && logicalHeightLength.isZero())) {
if (childrenInline())
return !hasLines();
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (child->isFloatingOrOutOfFlowPositioned())
continue;
if (!child->isSelfCollapsingBlock())
return false;
}
return true;
}
return false;
}
static inline UpdateScrollInfoAfterLayoutTransaction* currentUpdateScrollInfoAfterLayoutTransaction()
{
if (!updateScrollInfoAfterLayoutTransactionStack())
return nullptr;
return &updateScrollInfoAfterLayoutTransactionStack()->last();
}
void RenderBlock::beginUpdateScrollInfoAfterLayoutTransaction()
{
if (!updateScrollInfoAfterLayoutTransactionStack())
updateScrollInfoAfterLayoutTransactionStack() = std::make_unique<DelayedUpdateScrollInfoStack>();
if (updateScrollInfoAfterLayoutTransactionStack()->isEmpty() || currentUpdateScrollInfoAfterLayoutTransaction()->view != &view())
updateScrollInfoAfterLayoutTransactionStack()->append(UpdateScrollInfoAfterLayoutTransaction(view()));
++currentUpdateScrollInfoAfterLayoutTransaction()->nestedCount;
}
void RenderBlock::endAndCommitUpdateScrollInfoAfterLayoutTransaction()
{
UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
ASSERT(transaction);
ASSERT(transaction->view == &view());
if (--transaction->nestedCount)
return;
Vector<RenderBlock*> blocksToUpdate;
copyToVector(transaction->blocks, blocksToUpdate);
updateScrollInfoAfterLayoutTransactionStack()->removeLast();
if (updateScrollInfoAfterLayoutTransactionStack()->isEmpty())
updateScrollInfoAfterLayoutTransactionStack() = nullptr;
for (auto* block : blocksToUpdate) {
ASSERT(block->hasOverflowClip());
block->layer()->updateScrollInfoAfterLayout();
block->clearLayoutOverflow();
}
}
void RenderBlock::removeFromUpdateScrollInfoAfterLayoutTransaction()
{
if (UNLIKELY(updateScrollInfoAfterLayoutTransactionStack().get() != 0)) {
UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
ASSERT(transaction);
ASSERT(transaction->view == &view());
transaction->blocks.remove(this);
}
}
void RenderBlock::updateScrollInfoAfterLayout()
{
if (hasOverflowClip()) {
if (style().isFlippedBlocksWritingMode()) {
layer()->updateScrollInfoAfterLayout();
return;
}
UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
if (transaction && transaction->view == &view()) {
transaction->blocks.add(this);
return;
}
layer()->updateScrollInfoAfterLayout();
}
}
void RenderBlock::layout()
{
StackStats::LayoutCheckPoint layoutCheckPoint;
OverflowEventDispatcher dispatcher(this);
updateFirstLetter();
layoutBlock(false);
UpdateScrollInfoAfterLayoutTransaction* transaction = currentUpdateScrollInfoAfterLayoutTransaction();
bool isDelayingUpdateScrollInfoAfterLayoutInView = transaction && transaction->view == &view();
if (hasControlClip() && m_overflow && !isDelayingUpdateScrollInfoAfterLayoutInView)
clearLayoutOverflow();
invalidateBackgroundObscurationStatus();
}
static RenderBlockRareData* getRareData(const RenderBlock* block)
{
return gRareDataMap ? gRareDataMap->get(block) : 0;
}
static RenderBlockRareData& ensureRareData(const RenderBlock* block)
{
if (!gRareDataMap)
gRareDataMap = new RenderBlockRareDataMap;
auto& rareData = gRareDataMap->add(block, nullptr).iterator->value;
if (!rareData)
rareData = std::make_unique<RenderBlockRareData>();
return *rareData.get();
}
#if ENABLE(CSS_SHAPES)
void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
{
RenderBox::imageChanged(image);
if (!parent() || !everHadLayout())
return;
}
#endif
void RenderBlock::preparePaginationBeforeBlockLayout(bool& relayoutChildren)
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (flowThread)
flowThread->logicalWidthChangedInRegionsForBlock(this, relayoutChildren);
}
bool RenderBlock::recomputeLogicalWidth()
{
LayoutUnit oldWidth = logicalWidth();
updateLogicalWidth();
bool hasBorderOrPaddingLogicalWidthChanged = m_hasBorderOrPaddingLogicalWidthChanged;
m_hasBorderOrPaddingLogicalWidthChanged = false;
return oldWidth != logicalWidth() || hasBorderOrPaddingLogicalWidthChanged;
}
void RenderBlock::layoutBlock(bool, LayoutUnit)
{
ASSERT_NOT_REACHED();
clearNeedsLayout();
}
void RenderBlock::addOverflowFromChildren()
{
if (childrenInline())
addOverflowFromInlineChildren();
else
addOverflowFromBlockChildren();
if (m_overflow) {
if (RenderFlowThread* containingFlowThread = flowThreadContainingBlock())
containingFlowThread->addRegionsVisualOverflow(this, m_overflow->visualOverflowRect());
}
}
void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
{
clearOverflow();
addOverflowFromChildren();
addOverflowFromPositionedObjects();
if (hasOverflowClip()) {
LayoutRect clientRect(flippedClientBoxRect());
LayoutRect rectToApply;
if (isHorizontalWritingMode())
rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
else
rectToApply = LayoutRect(clientRect.x(), clientRect.y(), std::max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
addLayoutOverflow(rectToApply);
if (hasRenderOverflow())
m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
}
addVisualEffectOverflow();
addVisualOverflowFromTheme();
}
void RenderBlock::clearLayoutOverflow()
{
if (!m_overflow)
return;
if (visualOverflowRect() == borderBoxRect()) {
clearOverflow();
return;
}
m_overflow->setLayoutOverflow(borderBoxRect());
}
void RenderBlock::addOverflowFromBlockChildren()
{
for (auto child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (!child->isFloatingOrOutOfFlowPositioned())
addOverflowFromChild(child);
}
}
void RenderBlock::addOverflowFromPositionedObjects()
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
RenderBox* positionedObject = *it;
if (positionedObject->style().position() != FixedPosition) {
LayoutUnit x = positionedObject->x();
if (style().shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
x -= verticalScrollbarWidth();
addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
}
}
}
void RenderBlock::addVisualOverflowFromTheme()
{
if (!style().hasAppearance())
return;
FloatRect inflatedRect = borderBoxRect();
theme().adjustRepaintRect(*this, inflatedRect);
addVisualOverflow(pixelSnappedIntRect(LayoutRect(inflatedRect)));
if (RenderFlowThread* flowThread = flowThreadContainingBlock())
flowThread->addRegionsVisualOverflowFromTheme(this);
}
bool RenderBlock::expandsToEncloseOverhangingFloats() const
{
return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBoxIncludingDeprecated())
|| isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot() || isRenderFlowThread();
}
LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox& child, LayoutUnit childMarginStart, RenderRegion* region)
{
LayoutUnit startPosition = startOffsetForContent(region);
LayoutUnit oldPosition = startPosition + childMarginStart;
LayoutUnit newPosition = oldPosition;
LayoutUnit blockOffset = logicalTopForChild(child);
if (region)
blockOffset = std::max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
LayoutUnit startOff = startOffsetForLineInRegion(blockOffset, false, region, logicalHeightForChild(child));
if (style().textAlign() != WEBKIT_CENTER && !child.style().marginStartUsing(&style()).isAuto()) {
if (childMarginStart < 0)
startOff += childMarginStart;
newPosition = std::max(newPosition, startOff); } else if (startOff != startPosition)
newPosition = startOff + childMarginStart;
return newPosition - oldPosition;
}
void RenderBlock::setLogicalLeftForChild(RenderBox& child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode applyDelta)
{
if (isHorizontalWritingMode()) {
if (applyDelta == ApplyLayoutDelta)
view().addLayoutDelta(LayoutSize(child.x() - logicalLeft, 0));
child.setX(logicalLeft);
} else {
if (applyDelta == ApplyLayoutDelta)
view().addLayoutDelta(LayoutSize(0, child.y() - logicalLeft));
child.setY(logicalLeft);
}
}
void RenderBlock::setLogicalTopForChild(RenderBox& child, LayoutUnit logicalTop, ApplyLayoutDeltaMode applyDelta)
{
if (isHorizontalWritingMode()) {
if (applyDelta == ApplyLayoutDelta)
view().addLayoutDelta(LayoutSize(0, child.y() - logicalTop));
child.setY(logicalTop);
} else {
if (applyDelta == ApplyLayoutDelta)
view().addLayoutDelta(LayoutSize(child.x() - logicalTop, 0));
child.setX(logicalTop);
}
}
void RenderBlock::updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox& child)
{
if (relayoutChildren || (child.hasRelativeLogicalHeight() && !isRenderView()))
child.setChildNeedsLayout(MarkOnlyThis);
if (relayoutChildren && child.needsPreferredWidthsRecalculation())
child.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
}
void RenderBlock::dirtyForLayoutFromPercentageHeightDescendants()
{
if (!gPercentHeightDescendantsMap)
return;
TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this);
if (!descendants)
return;
for (auto it = descendants->begin(), end = descendants->end(); it != end; ++it) {
RenderBox* box = *it;
while (box != this) {
if (box->normalChildNeedsLayout())
break;
box->setChildNeedsLayout(MarkOnlyThis);
if (box->hasAspectRatio())
box->setPreferredLogicalWidthsDirty(true);
box = box->containingBlock();
ASSERT(box);
if (!box)
break;
}
}
}
void RenderBlock::simplifiedNormalFlowLayout()
{
if (childrenInline()) {
ListHashSet<RootInlineBox*> lineBoxes;
for (InlineWalker walker(*this); !walker.atEnd(); walker.advance()) {
RenderObject* o = walker.current();
if (!o->isOutOfFlowPositioned() && (o->isReplaced() || o->isFloating())) {
RenderBox& box = toRenderBox(*o);
box.layoutIfNeeded();
if (box.inlineBoxWrapper())
lineBoxes.add(&box.inlineBoxWrapper()->root());
} else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
o->clearNeedsLayout();
}
GlyphOverflowAndFallbackFontsMap textBoxDataMap;
for (auto it = lineBoxes.begin(), end = lineBoxes.end(); it != end; ++it) {
RootInlineBox* box = *it;
box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
}
} else {
for (auto box = firstChildBox(); box; box = box->nextSiblingBox()) {
if (!box->isOutOfFlowPositioned())
box->layoutIfNeeded();
}
}
}
bool RenderBlock::simplifiedLayout()
{
if ((!posChildNeedsLayout() && !needsSimplifiedNormalFlowLayout()) || normalChildNeedsLayout() || selfNeedsLayout())
return false;
LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
return false;
if (needsSimplifiedNormalFlowLayout())
simplifiedNormalFlowLayout();
if (isRenderFlowThread())
toRenderFlowThread(this)->applyBreakAfterContent(clientLogicalBottom());
bool canContainFixedPosObjects = canContainFixedPositionObjects();
if (posChildNeedsLayout() || canContainFixedPosObjects)
layoutPositionedObjects(false, !posChildNeedsLayout() && canContainFixedPosObjects);
LayoutUnit oldClientAfterEdge = hasRenderOverflow() ? m_overflow->layoutClientAfterEdge() : clientLogicalBottom();
computeOverflow(oldClientAfterEdge, true);
statePusher.pop();
updateLayerTransform();
updateScrollInfoAfterLayout();
clearNeedsLayout();
return true;
}
void RenderBlock::markFixedPositionObjectForLayoutIfNeeded(RenderObject& child)
{
if (child.style().position() != FixedPosition)
return;
bool hasStaticBlockPosition = child.style().hasStaticBlockPosition(isHorizontalWritingMode());
bool hasStaticInlinePosition = child.style().hasStaticInlinePosition(isHorizontalWritingMode());
if (!hasStaticBlockPosition && !hasStaticInlinePosition)
return;
auto o = child.parent();
while (o && !o->isRenderView() && o->style().position() != AbsolutePosition)
o = o->parent();
if (o->style().position() != AbsolutePosition)
return;
RenderBox& box = toRenderBox(child);
if (hasStaticInlinePosition) {
LogicalExtentComputedValues computedValues;
box.computeLogicalWidthInRegion(computedValues);
LayoutUnit newLeft = computedValues.m_position;
if (newLeft != box.logicalLeft())
box.setChildNeedsLayout(MarkOnlyThis);
} else if (hasStaticBlockPosition) {
LayoutUnit oldTop = box.logicalTop();
box.updateLogicalHeight();
if (box.logicalTop() != oldTop)
box.setChildNeedsLayout(MarkOnlyThis);
}
}
LayoutUnit RenderBlock::marginIntrinsicLogicalWidthForChild(RenderBox& child) const
{
Length marginLeft = child.style().marginStartUsing(&style());
Length marginRight = child.style().marginEndUsing(&style());
LayoutUnit margin = 0;
if (marginLeft.isFixed())
margin += marginLeft.value();
if (marginRight.isFixed())
margin += marginRight.value();
return margin;
}
void RenderBlock::layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly)
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
RenderBox& r = **it;
estimateRegionRangeForBoxChild(r);
markFixedPositionObjectForLayoutIfNeeded(r);
if (fixedPositionObjectsOnly) {
r.layoutIfNeeded();
continue;
}
if (relayoutChildren || (r.style().hasStaticBlockPosition(isHorizontalWritingMode()) && r.parent() != this))
r.setChildNeedsLayout(MarkOnlyThis);
if (relayoutChildren && r.needsPreferredWidthsRecalculation())
r.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
if (!r.needsLayout())
r.markForPaginationRelayoutIfNeeded();
if (r.needsPositionedMovementLayoutOnly() && r.tryLayoutDoingPositionedMovementOnly())
r.clearNeedsLayout();
LayoutUnit oldLogicalTop = 0;
bool needsBlockDirectionLocationSetBeforeLayout = r.needsLayout() && view().layoutState()->needsBlockDirectionLocationSetBeforeLayout();
if (needsBlockDirectionLocationSetBeforeLayout) {
if (isHorizontalWritingMode() == r.isHorizontalWritingMode())
r.updateLogicalHeight();
else
r.updateLogicalWidth();
oldLogicalTop = logicalTopForChild(r);
}
r.layoutIfNeeded();
if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
r.setChildNeedsLayout(MarkOnlyThis);
r.layoutIfNeeded();
}
if (updateRegionRangeForBoxChild(r)) {
r.setNeedsLayout(MarkOnlyThis);
r.layoutIfNeeded();
}
}
}
void RenderBlock::markPositionedObjectsForLayout()
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
RenderBox* r = *it;
r->setChildNeedsLayout();
}
}
void RenderBlock::markForPaginationRelayoutIfNeeded()
{
ASSERT(!needsLayout());
if (needsLayout())
return;
if (view().layoutState()->pageLogicalHeightChanged() || (view().layoutState()->pageLogicalHeight() && view().layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
setChildNeedsLayout(MarkOnlyThis);
}
void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
LayoutPoint adjustedPaintOffset = paintOffset + location();
PaintPhase phase = paintInfo.phase;
RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
if (namedFlowFragment && !namedFlowFragment->flowThread()->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
return;
if (!isRoot()) {
LayoutRect overflowBox = overflowRectForPaintRejection(namedFlowFragment);
flipForWritingMode(overflowBox);
overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
overflowBox.moveBy(adjustedPaintOffset);
if (!overflowBox.intersects(paintInfo.rect)
#if PLATFORM(IOS)
&& (!hasLayer() || !layer()->isComposited())
#endif
)
return;
}
bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
paintObject(paintInfo, adjustedPaintOffset);
if (pushedClip)
popContentsClip(paintInfo, phase, adjustedPaintOffset);
if (hasOverflowClip() && style().visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(*this) && !paintInfo.paintRootBackgroundOnly())
layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), pixelSnappedIntRect(paintInfo.rect));
}
void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (document().didLayoutWithPendingStylesheets() && !isRenderView())
return;
if (childrenInline())
paintInlineChildren(paintInfo, paintOffset);
else {
PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
PaintInfo paintInfoForChild(paintInfo);
paintInfoForChild.phase = newPhase;
paintInfoForChild.updateSubtreePaintRootForChildren(this);
bool usePrintRect = !view().printRect().isEmpty();
paintChildren(paintInfo, paintOffset, paintInfoForChild, usePrintRect);
}
}
void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
{
for (auto child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (!paintChild(*child, paintInfo, paintOffset, paintInfoForChild, usePrintRect))
return;
}
}
bool RenderBlock::paintChild(RenderBox& child, PaintInfo& paintInfo, const LayoutPoint& paintOffset, PaintInfo& paintInfoForChild, bool usePrintRect)
{
bool checkBeforeAlways = !childrenInline() && (usePrintRect && child.style().pageBreakBefore() == PBALWAYS);
LayoutUnit absoluteChildY = paintOffset.y() + child.y();
if (checkBeforeAlways
&& absoluteChildY > paintInfo.rect.y()
&& absoluteChildY < paintInfo.rect.maxY()) {
view().setBestTruncatedAt(absoluteChildY, this, true);
return false;
}
if (!child.isFloating() && child.isReplaced() && usePrintRect && child.height() <= view().printRect().height()) {
if (absoluteChildY + child.height() > view().printRect().maxY()) {
if (absoluteChildY < view().truncatedAt())
view().setBestTruncatedAt(absoluteChildY, &child);
if (absoluteChildY >= view().truncatedAt())
return false;
}
}
LayoutPoint childPoint = flipForWritingModeForChild(&child, paintOffset);
if (!child.hasSelfPaintingLayer() && !child.isFloating())
child.paint(paintInfoForChild, childPoint);
bool checkAfterAlways = !childrenInline() && (usePrintRect && child.style().pageBreakAfter() == PBALWAYS);
if (checkAfterAlways
&& (absoluteChildY + child.height()) > paintInfo.rect.y()
&& (absoluteChildY + child.height()) < paintInfo.rect.maxY()) {
view().setBestTruncatedAt(absoluteChildY + child.height() + std::max<LayoutUnit>(0, child.collapsedMarginAfter()), this, true);
return false;
}
return true;
}
void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
{
bool caretBrowsing = frame().settings().caretBrowsingEnabled();
RenderObject* caretPainter;
bool isContentEditable;
if (type == CursorCaret) {
caretPainter = frame().selection().caretRendererWithoutUpdatingLayout();
isContentEditable = frame().selection().selection().hasEditableStyle();
} else {
caretPainter = frame().page()->dragCaretController().caretRenderer();
isContentEditable = frame().page()->dragCaretController().isContentEditable();
}
if (caretPainter == this && (isContentEditable || caretBrowsing)) {
if (type == CursorCaret)
frame().selection().paintCaret(paintInfo.context, paintOffset, paintInfo.rect);
else
frame().page()->dragCaretController().paintDragCaret(&frame(), paintInfo.context, paintOffset, paintInfo.rect);
}
}
void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
PaintPhase paintPhase = paintInfo.phase;
if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style().visibility() == VISIBLE) {
if (hasBoxDecorations()) {
bool didClipToRegion = false;
RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
if (paintInfo.paintContainer && namedFlowFragment && paintInfo.paintContainer->isRenderNamedFlowThread()) {
paintInfo.context->save();
didClipToRegion = true;
paintInfo.context->clip(toRenderNamedFlowThread(paintInfo.paintContainer)->decorationsClipRectForBoxInNamedFlowFragment(*this, *namedFlowFragment));
}
paintBoxDecorations(paintInfo, paintOffset);
if (didClipToRegion)
paintInfo.context->restore();
}
}
if (paintPhase == PaintPhaseMask && style().visibility() == VISIBLE) {
paintMask(paintInfo, paintOffset);
return;
}
if (paintInfo.paintRootBackgroundOnly())
return;
LayoutPoint scrolledOffset = paintOffset;
scrolledOffset.move(-scrolledContentOffset());
if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style().visibility() == VISIBLE)
paintColumnRules(paintInfo, scrolledOffset);
if (paintPhase == PaintPhaseBlockBackground)
return;
if (paintPhase != PaintPhaseSelfOutline)
paintContents(paintInfo, scrolledOffset);
bool isPrinting = document().printing();
if (!isPrinting)
paintSelection(paintInfo, scrolledOffset);
if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip)
paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style().visibility() == VISIBLE)
paintOutline(paintInfo, LayoutRect(paintOffset, size()));
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
RenderInline* inlineCont = inlineElementContinuation();
if (inlineCont && inlineCont->hasOutline() && inlineCont->style().visibility() == VISIBLE) {
RenderInline* inlineRenderer = toRenderInline(inlineCont->element()->renderer());
RenderBlock* cb = containingBlock();
bool inlineEnclosedInSelfPaintingLayer = false;
for (RenderBoxModelObject* box = inlineRenderer; box != cb; box = &box->parent()->enclosingBoxModelObject()) {
if (box->hasSelfPaintingLayer()) {
inlineEnclosedInSelfPaintingLayer = true;
break;
}
}
if (!inlineEnclosedInSelfPaintingLayer && !hasLayer())
cb->addContinuationWithOutline(inlineRenderer);
else if (!inlineRenderer->firstLineBox() || (!inlineEnclosedInSelfPaintingLayer && hasLayer()))
inlineRenderer->paintOutline(paintInfo, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
}
paintContinuationOutlines(paintInfo, paintOffset);
}
if (paintPhase == PaintPhaseForeground) {
paintCaret(paintInfo, paintOffset, CursorCaret);
paintCaret(paintInfo, paintOffset, DragCaret);
}
}
RenderInline* RenderBlock::inlineElementContinuation() const
{
RenderBoxModelObject* continuation = this->continuation();
return continuation && continuation->isRenderInline() ? toRenderInline(continuation) : 0;
}
RenderBlock* RenderBlock::blockElementContinuation() const
{
RenderBoxModelObject* currentContinuation = continuation();
if (!currentContinuation || currentContinuation->isInline())
return 0;
RenderBlock* nextContinuation = toRenderBlock(currentContinuation);
if (nextContinuation->isAnonymousBlock())
return nextContinuation->blockElementContinuation();
return nextContinuation;
}
static ContinuationOutlineTableMap* continuationOutlineTable()
{
DEPRECATED_DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
return &table;
}
void RenderBlock::addContinuationWithOutline(RenderInline* flow)
{
ASSERT(!flow->layer() && !flow->isInlineElementContinuation());
ContinuationOutlineTableMap* table = continuationOutlineTable();
ListHashSet<RenderInline*>* continuations = table->get(this);
if (!continuations) {
continuations = new ListHashSet<RenderInline*>;
table->set(this, std::unique_ptr<ListHashSet<RenderInline*>>(continuations));
}
continuations->add(flow);
}
bool RenderBlock::paintsContinuationOutline(RenderInline* flow)
{
ContinuationOutlineTableMap* table = continuationOutlineTable();
if (table->isEmpty())
return false;
ListHashSet<RenderInline*>* continuations = table->get(this);
if (!continuations)
return false;
return continuations->contains(flow);
}
void RenderBlock::paintContinuationOutlines(PaintInfo& info, const LayoutPoint& paintOffset)
{
ContinuationOutlineTableMap* table = continuationOutlineTable();
if (table->isEmpty())
return;
std::unique_ptr<ListHashSet<RenderInline*>> continuations = table->take(this);
if (!continuations)
return;
LayoutPoint accumulatedPaintOffset = paintOffset;
ListHashSet<RenderInline*>::iterator end = continuations->end();
for (ListHashSet<RenderInline*>::iterator it = continuations->begin(); it != end; ++it) {
RenderInline* flow = *it;
RenderBlock* block = flow->containingBlock();
for ( ; block && block != this; block = block->containingBlock())
accumulatedPaintOffset.moveBy(block->location());
ASSERT(block);
flow->paintOutline(info, accumulatedPaintOffset);
}
}
bool RenderBlock::shouldPaintSelectionGaps() const
{
return selectionState() != SelectionNone && style().visibility() == VISIBLE && isSelectionRoot();
}
bool RenderBlock::isSelectionRoot() const
{
if (isPseudoElement())
return false;
ASSERT(element() || isAnonymous());
if (isTable())
return false;
if (isBody() || isRoot() || hasOverflowClip()
|| isPositioned() || isFloating()
|| isTableCell() || isInlineBlockOrInlineTable()
|| hasTransform() || hasReflection() || hasMask() || isWritingModeRoot()
|| isRenderFlowThread() || style().columnSpan() == ColumnSpanAll)
return true;
if (view().selectionStart()) {
Node* startElement = view().selectionStart()->node();
if (startElement && startElement->rootEditableElement() == element())
return true;
}
return false;
}
GapRects RenderBlock::selectionGapRectsForRepaint(const RenderLayerModelObject* repaintContainer)
{
ASSERT(!needsLayout());
if (!shouldPaintSelectionGaps())
return GapRects();
TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip | UseTransforms);
LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint()) - scrolledContentOffset();
LogicalSelectionOffsetCaches cache(*this);
LayoutUnit lastTop = 0;
LayoutUnit lastLeft = logicalLeftSelectionOffset(*this, lastTop, cache);
LayoutUnit lastRight = logicalRightSelectionOffset(*this, lastTop, cache);
return selectionGaps(*this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight, cache);
}
void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
#if ENABLE(TEXT_SELECTION)
if (shouldPaintSelectionGaps() && paintInfo.phase == PaintPhaseForeground) {
LogicalSelectionOffsetCaches cache(*this);
LayoutUnit lastTop = 0;
LayoutUnit lastLeft = logicalLeftSelectionOffset(*this, lastTop, cache);
LayoutUnit lastRight = logicalRightSelectionOffset(*this, lastTop, cache);
GraphicsContextStateSaver stateSaver(*paintInfo.context);
LayoutRect gapRectsBounds = selectionGaps(*this, paintOffset, LayoutSize(), lastTop, lastLeft, lastRight, cache, &paintInfo);
if (!gapRectsBounds.isEmpty()) {
if (RenderLayer* layer = enclosingLayer()) {
gapRectsBounds.moveBy(-paintOffset);
if (!hasLayer()) {
LayoutRect localBounds(gapRectsBounds);
flipForWritingMode(localBounds);
gapRectsBounds = localToContainerQuad(FloatRect(localBounds), &layer->renderer()).enclosingBoundingBox();
if (layer->renderer().isBox())
gapRectsBounds.move(layer->renderBox()->scrolledContentOffset());
}
layer->addBlockSelectionGapsBounds(gapRectsBounds);
}
}
}
#else
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(paintOffset);
#endif
}
static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoint& offset, TrackedRendererListHashSet* positionedObjects)
{
if (!positionedObjects)
return;
TrackedRendererListHashSet::const_iterator end = positionedObjects->end();
for (TrackedRendererListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
RenderBox* r = *it;
paintInfo->context->clipOut(IntRect(offset.x() + r->x(), offset.y() + r->y(), r->width(), r->height()));
}
}
LayoutUnit blockDirectionOffset(RenderBlock& rootBlock, const LayoutSize& offsetFromRootBlock)
{
return rootBlock.isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
}
LayoutUnit inlineDirectionOffset(RenderBlock& rootBlock, const LayoutSize& offsetFromRootBlock)
{
return rootBlock.isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
}
LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
{
LayoutRect result;
if (isHorizontalWritingMode())
result = logicalRect;
else
result = LayoutRect(logicalRect.y(), logicalRect.x(), logicalRect.height(), logicalRect.width());
flipForWritingMode(result);
result.moveBy(rootBlockPhysicalPosition);
return result;
}
GapRects RenderBlock::selectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
{
if (paintInfo) {
LayoutRect flippedBlockRect(offsetFromRootBlock.width(), offsetFromRootBlock.height(), width(), height());
rootBlock.flipForWritingMode(flippedBlockRect);
flippedBlockRect.moveBy(rootBlockPhysicalPosition);
clipOutPositionedObjects(paintInfo, flippedBlockRect.location(), positionedObjects());
if (isBody() || isRoot()) for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
}
GapRects result;
if (!isRenderBlockFlow()) return result;
if (hasTransform() || style().columnSpan() == ColumnSpanAll || isInFlowRenderFlowThread()) {
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight(), cache);
lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight(), cache);
return result;
}
RenderNamedFlowFragment* namedFlowFragment = currentRenderNamedFlowFragment();
if (paintInfo && namedFlowFragment && paintInfo->paintContainer->isRenderFlowThread()) {
if (!toRenderFlowThread(paintInfo->paintContainer)->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
return result;
}
if (childrenInline())
result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
else
result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, cache, paintInfo);
if (&rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd)) {
result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
lastLogicalTop, lastLogicalLeft, lastLogicalRight, logicalHeight(), cache, paintInfo));
}
return result;
}
GapRects RenderBlock::inlineSelectionGaps(RenderBlock&, const LayoutPoint&, const LayoutSize&, LayoutUnit&, LayoutUnit&, LayoutUnit&, const LogicalSelectionOffsetCaches&, const PaintInfo*)
{
ASSERT_NOT_REACHED();
return GapRects();
}
GapRects RenderBlock::blockSelectionGaps(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
{
GapRects result;
RenderBox* curr;
for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
if (!curr)
return result;
LogicalSelectionOffsetCaches childCache(*this, cache);
for (bool sawSelectionEnd = false; curr && !sawSelectionEnd; curr = curr->nextSiblingBox()) {
SelectionState childState = curr->selectionState();
if (childState == SelectionBoth || childState == SelectionEnd)
sawSelectionEnd = true;
if (curr->isFloatingOrOutOfFlowPositioned())
continue;
if (curr->isInFlowPositioned() && curr->hasLayer()) {
LayoutSize relOffset = curr->layer()->offsetForInFlowPosition();
if (relOffset.width() || relOffset.height())
continue;
}
bool paintsOwnSelection = curr->shouldPaintSelectionGaps() || curr->isTable(); bool fillBlockGaps = paintsOwnSelection || (curr->canBeSelectionLeaf() && childState != SelectionNone);
if (fillBlockGaps) {
if (childState == SelectionEnd || childState == SelectionInside) {
result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock,
lastLogicalTop, lastLogicalLeft, lastLogicalRight, curr->logicalTop(), cache, paintInfo));
}
if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
childState = SelectionNone;
bool leftGap, rightGap;
getSelectionGapInfo(childState, leftGap, rightGap);
if (leftGap)
result.uniteLeft(logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalLeft(), curr->logicalTop(), curr->logicalHeight(), cache, paintInfo));
if (rightGap)
result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), cache, paintInfo));
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom(), cache);
lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom(), cache);
} else if (childState != SelectionNone) {
result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()),
lastLogicalTop, lastLogicalLeft, lastLogicalRight, childCache, paintInfo));
}
}
return result;
}
LayoutRect RenderBlock::blockSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
{
LayoutUnit logicalTop = lastLogicalTop;
LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
if (logicalHeight <= 0)
return LayoutRect();
LayoutUnit logicalLeft = std::max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom, cache));
LayoutUnit logicalRight = std::min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom, cache));
LayoutUnit logicalWidth = logicalRight - logicalLeft;
if (logicalWidth <= 0)
return LayoutRect();
LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(pixelSnappedForPainting(gapRect, document().deviceScaleFactor()), selectionBackgroundColor(), style().colorSpace());
return gapRect;
}
LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
{
LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
LayoutUnit rootBlockLogicalLeft = std::max(logicalLeftSelectionOffset(rootBlock, logicalTop, cache), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight, cache));
LayoutUnit rootBlockLogicalRight = std::min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft,
std::min(logicalRightSelectionOffset(rootBlock, logicalTop, cache), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight, cache)));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= 0)
return LayoutRect();
LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(pixelSnappedForPainting(gapRect, document().deviceScaleFactor()), selObj->selectionBackgroundColor(), selObj->style().colorSpace());
return gapRect;
}
LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock& rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
{
LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
LayoutUnit rootBlockLogicalLeft = std::max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight,
std::max(logicalLeftSelectionOffset(rootBlock, logicalTop, cache), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight, cache)));
LayoutUnit rootBlockLogicalRight = std::min(logicalRightSelectionOffset(rootBlock, logicalTop, cache), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight, cache));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= 0)
return LayoutRect();
LayoutRect gapRect = rootBlock.logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(pixelSnappedForPainting(gapRect, document().deviceScaleFactor()), selObj->selectionBackgroundColor(), selObj->style().colorSpace());
return gapRect;
}
void RenderBlock::getSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
{
bool ltr = style().isLeftToRightDirection();
leftGap = (state == RenderObject::SelectionInside) ||
(state == RenderObject::SelectionEnd && ltr) ||
(state == RenderObject::SelectionStart && !ltr);
rightGap = (state == RenderObject::SelectionInside) ||
(state == RenderObject::SelectionStart && ltr) ||
(state == RenderObject::SelectionEnd && !ltr);
}
LayoutUnit RenderBlock::logicalLeftSelectionOffset(RenderBlock& rootBlock, LayoutUnit position, const LogicalSelectionOffsetCaches& cache)
{
LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
if (logicalLeft == logicalLeftOffsetForContent()) {
if (&rootBlock != this) return cache.containingBlockInfo(*this).logicalLeftSelectionOffset(rootBlock, position + logicalTop());
return logicalLeft;
}
RenderBlock* cb = this;
const LogicalSelectionOffsetCaches* currentCache = &cache;
while (cb != &rootBlock) {
logicalLeft += cb->logicalLeft();
ASSERT(currentCache);
auto info = currentCache->containingBlockInfo(*cb);
cb = info.block();
currentCache = info.cache();
}
return logicalLeft;
}
LayoutUnit RenderBlock::logicalRightSelectionOffset(RenderBlock& rootBlock, LayoutUnit position, const LogicalSelectionOffsetCaches& cache)
{
LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
if (logicalRight == logicalRightOffsetForContent()) {
if (&rootBlock != this) return cache.containingBlockInfo(*this).logicalRightSelectionOffset(rootBlock, position + logicalTop());
return logicalRight;
}
RenderBlock* cb = this;
const LogicalSelectionOffsetCaches* currentCache = &cache;
while (cb != &rootBlock) {
logicalRight += cb->logicalLeft();
ASSERT(currentCache);
auto info = currentCache->containingBlockInfo(*cb);
cb = info.block();
currentCache = info.cache();
}
return logicalRight;
}
RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
{
if (isSelectionRoot())
return 0;
const RenderElement* object = this;
RenderObject* sibling;
do {
sibling = object->previousSibling();
while (sibling && (!sibling->isRenderBlock() || toRenderBlock(sibling)->isSelectionRoot()))
sibling = sibling->previousSibling();
offset -= LayoutSize(toRenderBlock(object)->logicalLeft(), toRenderBlock(object)->logicalTop());
object = object->parent();
} while (!sibling && object && object->isRenderBlock() && !toRenderBlock(object)->isSelectionRoot());
if (!sibling)
return 0;
RenderBlock* beforeBlock = toRenderBlock(sibling);
offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
RenderObject* child = beforeBlock->lastChild();
while (child && child->isRenderBlock()) {
beforeBlock = toRenderBlock(child);
offset += LayoutSize(beforeBlock->logicalLeft(), beforeBlock->logicalTop());
child = beforeBlock->lastChild();
}
return beforeBlock;
}
void RenderBlock::insertIntoTrackedRendererMaps(RenderBox& descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
{
if (!descendantsMap) {
descendantsMap = new TrackedDescendantsMap;
containerMap = new TrackedContainerMap;
}
TrackedRendererListHashSet* descendantSet = descendantsMap->get(this);
if (!descendantSet) {
descendantSet = new TrackedRendererListHashSet;
descendantsMap->set(this, std::unique_ptr<TrackedRendererListHashSet>(descendantSet));
}
bool added = descendantSet->add(&descendant).isNewEntry;
if (!added) {
ASSERT(containerMap->get(&descendant));
ASSERT(containerMap->get(&descendant)->contains(this));
return;
}
HashSet<RenderBlock*>* containerSet = containerMap->get(&descendant);
if (!containerSet) {
containerSet = new HashSet<RenderBlock*>;
containerMap->set(&descendant, std::unique_ptr<HashSet<RenderBlock*>>(containerSet));
}
ASSERT(!containerSet->contains(this));
containerSet->add(this);
}
void RenderBlock::removeFromTrackedRendererMaps(RenderBox& descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
{
if (!descendantsMap)
return;
std::unique_ptr<HashSet<RenderBlock*>> containerSet = containerMap->take(&descendant);
if (!containerSet)
return;
for (auto it = containerSet->begin(), end = containerSet->end(); it != end; ++it) {
RenderBlock* container = *it;
TrackedDescendantsMap::iterator descendantsMapIterator = descendantsMap->find(container);
ASSERT(descendantsMapIterator != descendantsMap->end());
if (descendantsMapIterator == descendantsMap->end())
continue;
TrackedRendererListHashSet* descendantSet = descendantsMapIterator->value.get();
ASSERT(descendantSet->contains(&descendant));
descendantSet->remove(&descendant);
if (descendantSet->isEmpty())
descendantsMap->remove(descendantsMapIterator);
}
}
TrackedRendererListHashSet* RenderBlock::positionedObjects() const
{
if (gPositionedDescendantsMap)
return gPositionedDescendantsMap->get(this);
return 0;
}
void RenderBlock::insertPositionedObject(RenderBox& o)
{
ASSERT(!isAnonymousBlock());
if (o.isRenderFlowThread())
return;
insertIntoTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
}
void RenderBlock::removePositionedObject(RenderBox& o)
{
removeFromTrackedRendererMaps(o, gPositionedDescendantsMap, gPositionedContainerMap);
}
void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState containingBlockState)
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
Vector<RenderBox*, 16> deadObjects;
for (auto it = positionedDescendants->begin(), end = positionedDescendants->end(); it != end; ++it) {
RenderBox* r = *it;
if (!o || r->isDescendantOf(o)) {
if (containingBlockState == NewContainingBlock)
r->setChildNeedsLayout(MarkOnlyThis);
RenderElement* p = r->parent();
while (p && !p->isRenderBlock())
p = p->parent();
if (p)
p->setChildNeedsLayout();
deadObjects.append(r);
}
}
for (unsigned i = 0; i < deadObjects.size(); i++)
removePositionedObject(*deadObjects.at(i));
}
void RenderBlock::addPercentHeightDescendant(RenderBox& descendant)
{
insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
}
void RenderBlock::removePercentHeightDescendant(RenderBox& descendant)
{
removeFromTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
}
TrackedRendererListHashSet* RenderBlock::percentHeightDescendants() const
{
return gPercentHeightDescendantsMap ? gPercentHeightDescendantsMap->get(this) : 0;
}
bool RenderBlock::hasPercentHeightContainerMap()
{
return gPercentHeightContainerMap;
}
bool RenderBlock::hasPercentHeightDescendant(RenderBox& descendant)
{
ASSERT(gPercentHeightContainerMap);
return gPercentHeightContainerMap->contains(&descendant);
}
void RenderBlock::removePercentHeightDescendantIfNeeded(RenderBox& descendant)
{
if (!hasPercentHeightContainerMap())
return;
if (!hasPercentHeightDescendant(descendant))
return;
removePercentHeightDescendant(descendant);
}
void RenderBlock::clearPercentHeightDescendantsFrom(RenderBox& parent)
{
ASSERT(gPercentHeightContainerMap);
for (RenderObject* curr = parent.firstChild(); curr; curr = curr->nextInPreOrder(&parent)) {
if (!curr->isBox())
continue;
RenderBox& box = toRenderBox(*curr);
if (!hasPercentHeightDescendant(box))
continue;
removePercentHeightDescendant(box);
}
}
LayoutUnit RenderBlock::textIndentOffset() const
{
LayoutUnit cw = 0;
if (style().textIndent().isPercent())
cw = containingBlock()->availableLogicalWidth();
return minimumValueForLength(style().textIndent(), cw);
}
LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region) const
{
LayoutUnit logicalLeftOffset = style().isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
if (!region)
return logicalLeftOffset;
LayoutRect boxRect = borderBoxRectInRegion(region);
return logicalLeftOffset + (isHorizontalWritingMode() ? boxRect.x() : boxRect.y());
}
LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region) const
{
LayoutUnit logicalRightOffset = style().isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
logicalRightOffset += availableLogicalWidth();
if (!region)
return logicalRightOffset;
LayoutRect boxRect = borderBoxRectInRegion(region);
return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
}
LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
{
LayoutUnit left = offsetFromFloats;
if (applyTextIndent && style().isLeftToRightDirection())
left += textIndentOffset();
if (style().lineAlign() == LineAlignNone)
return left;
LayoutState* layoutState = view().layoutState();
if (!layoutState)
return left;
RenderBlock* lineGrid = layoutState->lineGrid();
if (!lineGrid || lineGrid->style().writingMode() != style().writingMode())
return left;
float maxCharWidth = lineGrid->style().font().primaryFont()->maxCharWidth();
if (!maxCharWidth)
return left;
LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
float remainder = fmodf(maxCharWidth - fmodf(left + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
left += remainder;
return left;
}
LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
{
LayoutUnit right = offsetFromFloats;
if (applyTextIndent && !style().isLeftToRightDirection())
right -= textIndentOffset();
if (style().lineAlign() == LineAlignNone)
return right;
LayoutState* layoutState = view().layoutState();
if (!layoutState)
return right;
RenderBlock* lineGrid = layoutState->lineGrid();
if (!lineGrid || lineGrid->style().writingMode() != style().writingMode())
return right;
float maxCharWidth = lineGrid->style().font().primaryFont()->maxCharWidth();
if (!maxCharWidth)
return right;
LayoutUnit lineGridOffset = lineGrid->isHorizontalWritingMode() ? layoutState->lineGridOffset().width(): layoutState->lineGridOffset().height();
LayoutUnit layoutOffset = lineGrid->isHorizontalWritingMode() ? layoutState->layoutOffset().width() : layoutState->layoutOffset().height();
float remainder = fmodf(fmodf(right + layoutOffset - lineGridOffset, maxCharWidth), maxCharWidth);
right -= ceilf(remainder);
return right;
}
bool RenderBlock::avoidsFloats() const
{
return RenderBox::avoidsFloats()
|| !style().hasAutoColumnCount()
|| !style().hasAutoColumnWidth()
|| style().hasFlowFrom();
}
bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
{
if (!scrollsOverflow())
return false;
return layer()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
}
Node* RenderBlock::nodeForHitTest() const
{
if (isRenderView())
return &document();
return isAnonymousBlockContinuation() ? continuation()->element() : element();
}
bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
LayoutPoint adjustedLocation(accumulatedOffset + location());
LayoutSize localOffset = toLayoutSize(adjustedLocation);
RenderFlowThread* flowThread = flowThreadContainingBlock();
RenderNamedFlowFragment* namedFlowFragment = flowThread ? toRenderNamedFlowFragment(flowThread->currentRegion()) : nullptr;
if (namedFlowFragment && !flowThread->objectShouldFragmentInFlowRegion(this, namedFlowFragment))
return false;
if (!isRenderView()) {
LayoutRect overflowBox = visualOverflowRect();
flipForWritingMode(overflowBox);
overflowBox.moveBy(adjustedLocation);
if (!locationInContainer.intersects(overflowBox))
return false;
}
if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && isPointInOverflowControl(result, locationInContainer.point(), adjustedLocation)) {
updateHitTestResult(result, locationInContainer.point() - localOffset);
if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer))
return true;
}
if (style().clipPath()) {
switch (style().clipPath()->type()) {
case ClipPathOperation::Shape: {
ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style().clipPath());
LayoutRect referenceBoxRect;
switch (clipPath->referenceBox()) {
case CSSBoxType::MarginBox:
referenceBoxRect = marginBoxRect();
break;
case CSSBoxType::BorderBox:
referenceBoxRect = borderBoxRect();
break;
case CSSBoxType::PaddingBox:
referenceBoxRect = paddingBoxRect();
break;
case CSSBoxType::ContentBox:
referenceBoxRect = contentBoxRect();
break;
case CSSBoxType::BoxMissing:
case CSSBoxType::Fill:
case CSSBoxType::Stroke:
case CSSBoxType::ViewBox:
referenceBoxRect = borderBoxRect();
}
if (!clipPath->pathForReferenceRect(referenceBoxRect).contains(locationInContainer.point() - localOffset, clipPath->windRule()))
return false;
break;
}
case ClipPathOperation::Reference:
case ClipPathOperation::Box:
break;
}
}
bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
bool useClip = (hasControlClip() || useOverflowClip);
bool checkChildren = !useClip || (hasControlClip() ? locationInContainer.intersects(controlClipRect(adjustedLocation)) : locationInContainer.intersects(overflowClipRect(adjustedLocation, namedFlowFragment, IncludeOverlayScrollbarSize)));
if (checkChildren) {
LayoutSize scrolledOffset(localOffset - scrolledContentOffset());
if (hitTestContents(request, result, locationInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
return true;
}
if (hitTestAction == HitTestFloat && hitTestFloats(request, result, locationInContainer, toLayoutPoint(scrolledOffset)))
return true;
}
if (!isRenderView() && style().hasBorderRadius()) {
LayoutRect borderRect = borderBoxRect();
borderRect.moveBy(adjustedLocation);
RoundedRect border = style().getRoundedBorderFor(borderRect);
if (!locationInContainer.intersects(border))
return false;
}
if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
LayoutRect boundsRect(adjustedLocation, size());
if (visibleToHitTesting() && locationInContainer.intersects(boundsRect)) {
updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - localOffset));
if (!result.addNodeToRectBasedTestResult(nodeForHitTest(), request, locationInContainer, boundsRect))
return true;
}
}
return false;
}
bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
if (childrenInline() && !isTable())
return hitTestInlineChildren(request, result, locationInContainer, accumulatedOffset, hitTestAction);
HitTestAction childHitTest = hitTestAction;
if (hitTestAction == HitTestChildBlockBackgrounds)
childHitTest = HitTestChildBlockBackground;
for (auto child = lastChildBox(); child; child = child->previousSiblingBox()) {
LayoutPoint childPoint = flipForWritingModeForChild(child, accumulatedOffset);
if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, locationInContainer, childPoint, childHitTest))
return true;
}
return false;
}
static inline bool isEditingBoundary(RenderElement* ancestor, RenderObject& child)
{
ASSERT(!ancestor || ancestor->nonPseudoElement());
ASSERT(child.nonPseudoNode());
return !ancestor || !ancestor->parent() || (ancestor->hasLayer() && ancestor->parent()->isRenderView())
|| ancestor->nonPseudoElement()->hasEditableStyle() == child.nonPseudoNode()->hasEditableStyle();
}
VisiblePosition positionForPointRespectingEditingBoundaries(RenderBlock& parent, RenderBox& child, const LayoutPoint& pointInParentCoordinates)
{
LayoutPoint childLocation = child.location();
if (child.isInFlowPositioned())
childLocation += child.offsetForInFlowPosition();
LayoutPoint pointInChildCoordinates(toLayoutPoint(pointInParentCoordinates - childLocation));
Element* childElement= child.nonPseudoElement();
if (!childElement)
return child.positionForPoint(pointInChildCoordinates, nullptr);
RenderElement* ancestor = &parent;
while (ancestor && !ancestor->nonPseudoElement())
ancestor = ancestor->parent();
if (isEditingBoundary(ancestor, child))
return child.positionForPoint(pointInChildCoordinates, nullptr);
#if PLATFORM(IOS)
if (childElement->isContentEditable() && !ancestor->element()->isContentEditable())
return child.positionForPoint(pointInChildCoordinates, nullptr);
#endif
LayoutUnit childMiddle = parent.logicalWidthForChild(child) / 2;
LayoutUnit logicalLeft = parent.isHorizontalWritingMode() ? pointInChildCoordinates.x() : pointInChildCoordinates.y();
if (logicalLeft < childMiddle)
return ancestor->createVisiblePosition(childElement->nodeIndex(), DOWNSTREAM);
return ancestor->createVisiblePosition(childElement->nodeIndex() + 1, UPSTREAM);
}
VisiblePosition RenderBlock::positionForPointWithInlineChildren(const LayoutPoint&, const RenderRegion*)
{
ASSERT_NOT_REACHED();
return VisiblePosition();
}
static inline bool isChildHitTestCandidate(const RenderBox& box)
{
return box.height() && box.style().visibility() == VISIBLE && !box.isFloatingOrOutOfFlowPositioned() && !box.isInFlowRenderFlowThread();
}
static inline bool isChildHitTestCandidate(const RenderBox& box, const RenderRegion* region, const LayoutPoint& point)
{
if (!isChildHitTestCandidate(box))
return false;
if (!region)
return true;
const RenderBlock& block = box.isRenderBlock() ? toRenderBlock(box) : *box.containingBlock();
return block.regionAtBlockOffset(point.y()) == region;
}
VisiblePosition RenderBlock::positionForPoint(const LayoutPoint& point, const RenderRegion* region)
{
if (isTable())
return RenderBox::positionForPoint(point, region);
if (isReplaced()) {
LayoutUnit pointLogicalLeft = isHorizontalWritingMode() ? point.x() : point.y();
LayoutUnit pointLogicalTop = isHorizontalWritingMode() ? point.y() : point.x();
if (pointLogicalTop < 0 || (pointLogicalTop < logicalHeight() && pointLogicalLeft < 0))
return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
if (pointLogicalTop >= logicalHeight() || (pointLogicalTop >= 0 && pointLogicalLeft >= logicalWidth()))
return createVisiblePosition(caretMaxOffset(), DOWNSTREAM);
}
LayoutPoint pointInContents = point;
offsetForContents(pointInContents);
LayoutPoint pointInLogicalContents(pointInContents);
if (!isHorizontalWritingMode())
pointInLogicalContents = pointInLogicalContents.transposedPoint();
if (childrenInline())
return positionForPointWithInlineChildren(pointInLogicalContents, region);
RenderBox* lastCandidateBox = lastChildBox();
if (!region)
region = regionAtBlockOffset(pointInLogicalContents.y());
while (lastCandidateBox && !isChildHitTestCandidate(*lastCandidateBox, region, pointInLogicalContents))
lastCandidateBox = lastCandidateBox->previousSiblingBox();
bool blocksAreFlipped = style().isFlippedBlocksWritingMode();
if (lastCandidateBox) {
if (pointInLogicalContents.y() > logicalTopForChild(*lastCandidateBox)
|| (!blocksAreFlipped && pointInLogicalContents.y() == logicalTopForChild(*lastCandidateBox)))
return positionForPointRespectingEditingBoundaries(*this, *lastCandidateBox, pointInContents);
for (auto childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
if (!isChildHitTestCandidate(*childBox, region, pointInLogicalContents))
continue;
LayoutUnit childLogicalBottom = logicalTopForChild(*childBox) + logicalHeightForChild(*childBox);
if (isChildHitTestCandidate(*childBox, region, pointInLogicalContents) && (pointInLogicalContents.y() < childLogicalBottom
|| (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
return positionForPointRespectingEditingBoundaries(*this, *childBox, pointInContents);
}
}
return RenderBox::positionForPoint(point, region);
}
void RenderBlock::offsetForContents(LayoutPoint& offset) const
{
offset = flipForWritingMode(offset);
offset += scrolledContentOffset();
offset = flipForWritingMode(offset);
}
void RenderBlock::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
ASSERT(!childrenInline());
computeBlockPreferredLogicalWidths(minLogicalWidth, maxLogicalWidth);
maxLogicalWidth = std::max(minLogicalWidth, maxLogicalWidth);
int scrollbarWidth = instrinsicScrollbarLogicalWidth();
maxLogicalWidth += scrollbarWidth;
minLogicalWidth += scrollbarWidth;
}
void RenderBlock::computePreferredLogicalWidths()
{
ASSERT(preferredLogicalWidthsDirty());
updateFirstLetter();
m_minPreferredLogicalWidth = 0;
m_maxPreferredLogicalWidth = 0;
const RenderStyle& styleToUse = style();
if (!isTableCell() && styleToUse.logicalWidth().isFixed() && styleToUse.logicalWidth().value() >= 0
&& !(isDeprecatedFlexItem() && !styleToUse.logicalWidth().intValue()))
m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalWidth().value());
else
computeIntrinsicLogicalWidths(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
if (styleToUse.logicalMinWidth().isFixed() && styleToUse.logicalMinWidth().value() > 0) {
m_maxPreferredLogicalWidth = std::max(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
m_minPreferredLogicalWidth = std::max(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMinWidth().value()));
}
if (styleToUse.logicalMaxWidth().isFixed()) {
m_maxPreferredLogicalWidth = std::min(m_maxPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
m_minPreferredLogicalWidth = std::min(m_minPreferredLogicalWidth, adjustContentBoxLogicalWidthForBoxSizing(styleToUse.logicalMaxWidth().value()));
}
if (isTableCell()) {
m_minPreferredLogicalWidth = m_minPreferredLogicalWidth.ceil();
m_maxPreferredLogicalWidth = m_maxPreferredLogicalWidth.ceil();
}
LayoutUnit borderAndPadding = borderAndPaddingLogicalWidth();
m_minPreferredLogicalWidth += borderAndPadding;
m_maxPreferredLogicalWidth += borderAndPadding;
setPreferredLogicalWidthsDirty(false);
}
struct InlineMinMaxIterator {
RenderObject* parent;
RenderObject* current;
bool endOfInline;
InlineMinMaxIterator(RenderObject* p, bool end = false)
:parent(p), current(p), endOfInline(end) {}
RenderObject* next();
};
RenderObject* InlineMinMaxIterator::next()
{
RenderObject* result = 0;
bool oldEndOfInline = endOfInline;
endOfInline = false;
while (current || current == parent) {
if (!oldEndOfInline &&
(current == parent ||
(!current->isFloating() && !current->isReplaced() && !current->isOutOfFlowPositioned())))
result = current->firstChildSlow();
if (!result) {
if (!oldEndOfInline && current->isRenderInline()) {
result = current;
endOfInline = true;
break;
}
while (current && current != parent) {
result = current->nextSibling();
if (result) break;
current = current->parent();
if (current && current != parent && current->isRenderInline()) {
result = current;
endOfInline = true;
break;
}
}
}
if (!result)
break;
if (!result->isOutOfFlowPositioned() && (result->isTextOrLineBreak() || result->isFloating() || result->isReplaced() || result->isRenderInline()))
break;
current = result;
result = 0;
}
current = result;
return current;
}
static LayoutUnit getBPMWidth(LayoutUnit childValue, Length cssUnit)
{
if (cssUnit.type() != Auto)
return (cssUnit.isFixed() ? LayoutUnit(cssUnit.value()) : childValue);
return 0;
}
static LayoutUnit getBorderPaddingMargin(const RenderBoxModelObject* child, bool endOfInline)
{
const RenderStyle& childStyle = child->style();
if (endOfInline)
return getBPMWidth(child->marginEnd(), childStyle.marginEnd()) +
getBPMWidth(child->paddingEnd(), childStyle.paddingEnd()) +
child->borderEnd();
return getBPMWidth(child->marginStart(), childStyle.marginStart()) +
getBPMWidth(child->paddingStart(), childStyle.paddingStart()) +
child->borderStart();
}
static inline void stripTrailingSpace(float& inlineMax, float& inlineMin,
RenderObject* trailingSpaceChild)
{
if (trailingSpaceChild && trailingSpaceChild->isText()) {
RenderText* t = toRenderText(trailingSpaceChild);
const UChar space = ' ';
const Font& font = t->style().font(); float spaceWidth = font.width(RenderBlock::constructTextRun(t, font, &space, 1, t->style()));
inlineMax -= spaceWidth + font.wordSpacing();
if (inlineMin > inlineMax)
inlineMin = inlineMax;
}
}
static inline void updatePreferredWidth(LayoutUnit& preferredWidth, float& result)
{
LayoutUnit snappedResult = ceiledLayoutUnit(result);
preferredWidth = std::max(snappedResult, preferredWidth);
}
static inline LayoutUnit adjustFloatForSubPixelLayout(float value)
{
#if ENABLE(SUBPIXEL_LAYOUT)
return ceiledLayoutUnit(value);
#else
return static_cast<int>(value);
#endif
}
void RenderBlock::computeInlinePreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth)
{
float inlineMax = 0;
float inlineMin = 0;
const RenderStyle& styleToUse = style();
RenderBlock* containingBlock = this->containingBlock();
LayoutUnit cw = containingBlock ? containingBlock->contentLogicalWidth() : LayoutUnit();
bool stripFrontSpaces = true;
RenderObject* trailingSpaceChild = 0;
bool allowImagesToBreak = !document().inQuirksMode() || !isTableCell() || !styleToUse.logicalWidth().isIntrinsicOrAuto();
bool autoWrap, oldAutoWrap;
autoWrap = oldAutoWrap = styleToUse.autoWrap();
InlineMinMaxIterator childIterator(this);
bool addedTextIndent = false;
bool hasRemainingNegativeTextIndent = false;
LayoutUnit textIndent = minimumValueForLength(styleToUse.textIndent(), cw);
RenderObject* prevFloat = 0;
bool isPrevChildInlineFlow = false;
bool shouldBreakLineAfterText = false;
while (RenderObject* child = childIterator.next()) {
autoWrap = child->isReplaced() ? child->parent()->style().autoWrap() :
child->style().autoWrap();
if (!child->isBR()) {
const RenderStyle& childStyle = child->style();
float childMin = 0;
float childMax = 0;
if (!child->isText()) {
if (child->isLineBreakOpportunity()) {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = 0;
continue;
}
if (child->isRenderInline()) {
float bpm = getBorderPaddingMargin(toRenderInline(child), childIterator.endOfInline);
childMin += bpm;
childMax += bpm;
inlineMin += childMin;
inlineMax += childMax;
child->setPreferredLogicalWidthsDirty(false);
} else {
LayoutUnit margins = 0;
Length startMargin = childStyle.marginStart();
Length endMargin = childStyle.marginEnd();
if (startMargin.isFixed())
margins += adjustFloatForSubPixelLayout(startMargin.value());
if (endMargin.isFixed())
margins += adjustFloatForSubPixelLayout(endMargin.value());
childMin += margins.ceilToFloat();
childMax += margins.ceilToFloat();
}
}
if (!child->isRenderInline() && !child->isText()) {
childMin += child->minPreferredLogicalWidth().ceilToFloat();
childMax += child->maxPreferredLogicalWidth().ceilToFloat();
bool clearPreviousFloat;
if (child->isFloating()) {
clearPreviousFloat = (prevFloat
&& ((prevFloat->style().floating() == LeftFloat && (childStyle.clear() & CLEFT))
|| (prevFloat->style().floating() == RightFloat && (childStyle.clear() & CRIGHT))));
prevFloat = child;
} else
clearPreviousFloat = false;
bool canBreakReplacedElement = !child->isImage() || allowImagesToBreak;
if ((canBreakReplacedElement && (autoWrap || oldAutoWrap) && (!isPrevChildInlineFlow || shouldBreakLineAfterText)) || clearPreviousFloat) {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = 0;
}
if (clearPreviousFloat) {
updatePreferredWidth(maxLogicalWidth, inlineMax);
inlineMax = 0;
}
if (!addedTextIndent && !child->isFloating()) {
LayoutUnit ceiledIndent = textIndent.ceilToFloat();
childMin += ceiledIndent;
childMax += ceiledIndent;
if (childMin < 0)
textIndent = adjustFloatForSubPixelLayout(childMin);
else
addedTextIndent = true;
}
inlineMax += std::max<float>(0, childMax);
if (!autoWrap || !canBreakReplacedElement || (isPrevChildInlineFlow && !shouldBreakLineAfterText)) {
if (child->isFloating())
updatePreferredWidth(minLogicalWidth, childMin);
else
inlineMin += childMin;
} else {
updatePreferredWidth(minLogicalWidth, childMin);
inlineMin = 0;
}
if (autoWrap && canBreakReplacedElement && isPrevChildInlineFlow) {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = 0;
}
if (!child->isFloating()) {
stripFrontSpaces = false;
trailingSpaceChild = 0;
}
} else if (child->isText()) {
RenderText* t = toRenderText(child);
if (t->style().hasTextCombine() && t->isCombineText())
toRenderCombineText(*t).combineText();
bool hasBreakableChar, hasBreak;
float beginMin, endMin;
bool beginWS, endWS;
float beginMax, endMax;
t->trimmedPrefWidths(inlineMax, beginMin, beginWS, endMin, endWS,
hasBreakableChar, hasBreak, beginMax, endMax,
childMin, childMax, stripFrontSpaces);
if (!hasBreak && childMax == 0) {
if (autoWrap && (beginWS || endWS)) {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = 0;
}
continue;
}
if (stripFrontSpaces)
trailingSpaceChild = child;
else
trailingSpaceChild = 0;
float ti = 0;
if (!addedTextIndent || hasRemainingNegativeTextIndent) {
ti = textIndent.ceilToFloat();
childMin += ti;
beginMin += ti;
if (!addedTextIndent) {
childMax += ti;
beginMax += ti;
addedTextIndent = true;
}
if (childMin < 0) {
textIndent = childMin;
hasRemainingNegativeTextIndent = true;
}
}
if (!hasBreakableChar) {
inlineMin += childMin;
} else {
if (beginWS)
updatePreferredWidth(minLogicalWidth, inlineMin);
else {
inlineMin += beginMin;
updatePreferredWidth(minLogicalWidth, inlineMin);
childMin -= ti;
}
inlineMin = childMin;
if (endWS) {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = 0;
shouldBreakLineAfterText = false;
} else {
updatePreferredWidth(minLogicalWidth, inlineMin);
inlineMin = endMin;
shouldBreakLineAfterText = true;
}
}
if (hasBreak) {
inlineMax += beginMax;
updatePreferredWidth(maxLogicalWidth, inlineMax);
updatePreferredWidth(maxLogicalWidth, childMax);
inlineMax = endMax;
addedTextIndent = true;
} else
inlineMax += std::max<float>(0, childMax);
}
if (child->isListMarker())
stripFrontSpaces = true;
} else {
updatePreferredWidth(minLogicalWidth, inlineMin);
updatePreferredWidth(maxLogicalWidth, inlineMax);
inlineMin = inlineMax = 0;
stripFrontSpaces = true;
trailingSpaceChild = 0;
addedTextIndent = true;
}
if (!child->isText() && child->isRenderInline())
isPrevChildInlineFlow = true;
else
isPrevChildInlineFlow = false;
oldAutoWrap = autoWrap;
}
if (styleToUse.collapseWhiteSpace())
stripTrailingSpace(inlineMax, inlineMin, trailingSpaceChild);
updatePreferredWidth(minLogicalWidth, inlineMin);
updatePreferredWidth(maxLogicalWidth, inlineMax);
}
void RenderBlock::computeBlockPreferredLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const
{
const RenderStyle& styleToUse = style();
bool nowrap = styleToUse.whiteSpace() == NOWRAP;
RenderObject* child = firstChild();
RenderBlock* containingBlock = this->containingBlock();
LayoutUnit floatLeftWidth = 0, floatRightWidth = 0;
while (child) {
if (child->isOutOfFlowPositioned()) {
child = child->nextSibling();
continue;
}
const RenderStyle& childStyle = child->style();
if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
if (childStyle.clear() & CLEFT) {
maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
floatLeftWidth = 0;
}
if (childStyle.clear() & CRIGHT) {
maxLogicalWidth = std::max(floatTotalWidth, maxLogicalWidth);
floatRightWidth = 0;
}
}
Length startMarginLength = childStyle.marginStartUsing(&styleToUse);
Length endMarginLength = childStyle.marginEndUsing(&styleToUse);
LayoutUnit margin = 0;
LayoutUnit marginStart = 0;
LayoutUnit marginEnd = 0;
if (startMarginLength.isFixed())
marginStart += startMarginLength.value();
if (endMarginLength.isFixed())
marginEnd += endMarginLength.value();
margin = marginStart + marginEnd;
LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
RenderBox* childBox = toRenderBox(child);
LogicalExtentComputedValues computedValues;
childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
} else {
childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
}
LayoutUnit w = childMinPreferredLogicalWidth + margin;
minLogicalWidth = std::max(w, minLogicalWidth);
if (nowrap && !child->isTable())
maxLogicalWidth = std::max(w, maxLogicalWidth);
w = childMaxPreferredLogicalWidth + margin;
if (!child->isFloating()) {
if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
bool ltr = containingBlock ? containingBlock->style().isLeftToRightDirection() : styleToUse.isLeftToRightDirection();
LayoutUnit marginLogicalLeft = ltr ? marginStart : marginEnd;
LayoutUnit marginLogicalRight = ltr ? marginEnd : marginStart;
LayoutUnit maxLeft = marginLogicalLeft > 0 ? std::max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
LayoutUnit maxRight = marginLogicalRight > 0 ? std::max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
w = std::max(w, floatLeftWidth + floatRightWidth);
}
else
maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
floatLeftWidth = floatRightWidth = 0;
}
if (child->isFloating()) {
if (childStyle.floating() == LeftFloat)
floatLeftWidth += w;
else
floatRightWidth += w;
} else
maxLogicalWidth = std::max(w, maxLogicalWidth);
child = child->nextSibling();
}
minLogicalWidth = std::max<LayoutUnit>(0, minLogicalWidth);
maxLogicalWidth = std::max<LayoutUnit>(0, maxLogicalWidth);
maxLogicalWidth = std::max(floatLeftWidth + floatRightWidth, maxLogicalWidth);
}
bool RenderBlock::hasLineIfEmpty() const
{
if (!element())
return false;
if (element()->isRootEditableElement())
return true;
return false;
}
LayoutUnit RenderBlock::lineHeight(bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
{
if (isReplaced() && linePositionMode == PositionOnContainingLine)
return RenderBox::lineHeight(firstLine, direction, linePositionMode);
if (firstLine && document().styleSheetCollection().usesFirstLineRules()) {
RenderStyle& s = firstLine ? firstLineStyle() : style();
if (&s != &style())
return s.computedLineHeight();
}
if (m_lineHeight == -1)
m_lineHeight = style().computedLineHeight();
return m_lineHeight;
}
int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, LineDirectionMode direction, LinePositionMode linePositionMode) const
{
if (isReplaced() && linePositionMode == PositionOnContainingLine) {
if (style().hasAppearance() && !theme().isControlContainer(style().appearance()))
return theme().baselinePosition(*this);
bool ignoreBaseline = (layer() && (layer()->marquee() || (direction == HorizontalLine ? (layer()->verticalScrollbar() || layer()->scrollYOffset() != 0)
: (layer()->horizontalScrollbar() || layer()->scrollXOffset() != 0)))) || (isWritingModeRoot() && !isRubyRun());
int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
LayoutUnit bottomOfContent = direction == HorizontalLine ? borderTop() + paddingTop() + contentHeight() : borderRight() + paddingRight() + contentWidth();
if (baselinePos != -1 && baselinePos <= bottomOfContent)
return direction == HorizontalLine ? marginTop() + baselinePos : marginRight() + baselinePos;
return RenderBox::baselinePosition(baselineType, firstLine, direction, linePositionMode);
}
const RenderStyle& style = firstLine ? firstLineStyle() : this->style();
const FontMetrics& fontMetrics = style.fontMetrics();
return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
}
LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
{
if (!document().inNoQuirksMode() && replacedHeight)
return replacedHeight;
const RenderStyle& style = isFirstLine ? firstLineStyle() : this->style();
if (!(style.lineBoxContain() & LineBoxContainBlock))
return 0;
return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
}
int RenderBlock::firstLineBaseline() const
{
if (isWritingModeRoot() && !isRubyRun())
return -1;
for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
if (!curr->isFloatingOrOutOfFlowPositioned()) {
int result = curr->firstLineBaseline();
if (result != -1)
return curr->logicalTop() + result; }
}
return -1;
}
int RenderBlock::inlineBlockBaseline(LineDirectionMode lineDirection) const
{
if (isWritingModeRoot() && !isRubyRun())
return -1;
bool haveNormalFlowChild = false;
for (auto box = lastChildBox(); box; box = box->previousSiblingBox()) {
if (box->isFloatingOrOutOfFlowPositioned())
continue;
haveNormalFlowChild = true;
int result = box->inlineBlockBaseline(lineDirection);
if (result != -1)
return box->logicalTop() + result; }
if (!haveNormalFlowChild && hasLineIfEmpty()) {
auto& fontMetrics = firstLineStyle().fontMetrics();
return fontMetrics.ascent()
+ (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
+ (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
}
return -1;
}
RenderBlock* RenderBlock::firstLineBlock() const
{
RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
bool hasPseudo = false;
while (true) {
hasPseudo = firstLineBlock->style().hasPseudoStyle(FIRST_LINE);
if (hasPseudo)
break;
RenderElement* parentBlock = firstLineBlock->parent();
if (firstLineBlock->isReplaced() || firstLineBlock->isFloating()
|| !parentBlock || parentBlock->firstChild() != firstLineBlock || (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
break;
firstLineBlock = toRenderBlock(parentBlock);
}
if (!hasPseudo)
return 0;
return firstLineBlock;
}
static RenderStyle* styleForFirstLetter(RenderObject* firstLetterBlock, RenderObject* firstLetterContainer)
{
RenderStyle* pseudoStyle = firstLetterBlock->getCachedPseudoStyle(FIRST_LETTER, &firstLetterContainer->firstLineStyle());
pseudoStyle->setDisplay(pseudoStyle->isFloating() ? BLOCK : INLINE);
pseudoStyle->setPosition(StaticPosition);
return pseudoStyle;
}
static inline bool isPunctuationForFirstLetter(UChar c)
{
return U_GET_GC_MASK(c) & (U_GC_PS_MASK | U_GC_PE_MASK | U_GC_PI_MASK | U_GC_PF_MASK | U_GC_PO_MASK);
}
static inline bool shouldSkipForFirstLetter(UChar c)
{
return isSpaceOrNewline(c) || c == noBreakSpace || isPunctuationForFirstLetter(c);
}
static inline RenderBlock* findFirstLetterBlock(RenderBlock* start)
{
RenderBlock* firstLetterBlock = start;
while (true) {
bool canHaveFirstLetterRenderer = firstLetterBlock->style().hasPseudoStyle(FIRST_LETTER)
&& firstLetterBlock->canHaveGeneratedChildren()
&& (!firstLetterBlock->isFlexibleBox() || firstLetterBlock->isRenderButton());
if (canHaveFirstLetterRenderer)
return firstLetterBlock;
RenderElement* parentBlock = firstLetterBlock->parent();
if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock
|| (!parentBlock->isRenderBlockFlow() && !parentBlock->isRenderButton()))
return 0;
firstLetterBlock = toRenderBlock(parentBlock);
}
return 0;
}
void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
{
RenderElement* firstLetter = currentChild->parent();
RenderElement* firstLetterContainer = firstLetter->parent();
RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
ASSERT(firstLetter->isFloating() || firstLetter->isInline());
if (Style::determineChange(&firstLetter->style(), pseudoStyle) == Style::Detach) {
RenderBoxModelObject* newFirstLetter;
if (pseudoStyle->display() == INLINE)
newFirstLetter = new RenderInline(document(), *pseudoStyle);
else
newFirstLetter = new RenderBlockFlow(document(), *pseudoStyle);
newFirstLetter->initializeStyle();
LayoutStateDisabler layoutStateDisabler(&view());
while (RenderObject* child = firstLetter->firstChild()) {
if (child->isText())
toRenderText(child)->removeAndDestroyTextBoxes();
firstLetter->removeChild(*child);
newFirstLetter->addChild(child, 0);
}
RenderObject* nextSibling = firstLetter->nextSibling();
if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
ASSERT(remainingText->isAnonymous() || remainingText->textNode()->renderer() == remainingText);
remainingText->setFirstLetter(*newFirstLetter);
newFirstLetter->setFirstLetterRemainingText(remainingText);
}
firstLetterContainer->removeChildInternal(*firstLetter, NotifyChildren);
firstLetter->destroy();
firstLetter = newFirstLetter;
firstLetterContainer->addChild(firstLetter, nextSibling);
} else
firstLetter->setStyle(*pseudoStyle);
}
void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderText* currentTextChild)
{
RenderElement* firstLetterContainer = currentTextChild->parent();
RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
RenderBoxModelObject* firstLetter = 0;
if (pseudoStyle->display() == INLINE)
firstLetter = new RenderInline(document(), *pseudoStyle);
else
firstLetter = new RenderBlockFlow(document(), *pseudoStyle);
firstLetter->initializeStyle();
firstLetterContainer->addChild(firstLetter, currentTextChild);
String oldText = currentTextChild->originalText();
ASSERT(!oldText.isNull());
if (!oldText.isEmpty()) {
unsigned length = 0;
while (length < oldText.length() && shouldSkipForFirstLetter(oldText[length]))
length++;
length++;
for (unsigned scanLength = length; scanLength < oldText.length(); ++scanLength) {
UChar c = oldText[scanLength];
if (!shouldSkipForFirstLetter(c))
break;
if (isPunctuationForFirstLetter(c))
length = scanLength + 1;
}
RenderTextFragment* remainingText;
if (currentTextChild->textNode())
remainingText = new RenderTextFragment(*currentTextChild->textNode(), oldText, length, oldText.length() - length);
else
remainingText = new RenderTextFragment(document(), oldText, length, oldText.length() - length);
if (remainingText->textNode())
remainingText->textNode()->setRenderer(remainingText);
firstLetterContainer->addChild(remainingText, currentTextChild);
firstLetterContainer->removeChild(*currentTextChild);
remainingText->setFirstLetter(*firstLetter);
firstLetter->setFirstLetterRemainingText(remainingText);
RenderTextFragment* letter;
if (remainingText->textNode())
letter = new RenderTextFragment(*remainingText->textNode(), oldText, 0, length);
else
letter = new RenderTextFragment(document(), oldText, 0, length);
firstLetter->addChild(letter);
currentTextChild->destroy();
}
}
void RenderBlock::getFirstLetter(RenderObject*& firstLetter, RenderElement*& firstLetterContainer, RenderObject* skipObject)
{
firstLetter = nullptr;
firstLetterContainer = nullptr;
if (!document().styleSheetCollection().usesFirstLetterRules())
return;
if (style().styleType() == FIRST_LETTER)
return;
firstLetterContainer = findFirstLetterBlock(this);
if (!firstLetterContainer)
return;
firstLetter = firstLetterContainer->firstChild();
while (firstLetter) {
if (firstLetter->isText()) {
if (firstLetter == skipObject) {
firstLetter = firstLetter->nextSibling();
continue;
}
break;
}
RenderElement& current = toRenderElement(*firstLetter);
if (current.isListMarker())
firstLetter = current.nextSibling();
else if (current.isFloatingOrOutOfFlowPositioned()) {
if (current.style().styleType() == FIRST_LETTER) {
firstLetter = current.firstChild();
break;
}
firstLetter = current.nextSibling();
} else if (current.isReplaced() || current.isRenderButton() || current.isMenuList())
break;
else if (current.style().hasPseudoStyle(FIRST_LETTER) && current.canHaveGeneratedChildren()) {
firstLetterContainer = ¤t;
firstLetter = current.firstChild();
} else
firstLetter = current.firstChild();
}
if (!firstLetter)
firstLetterContainer = nullptr;
}
void RenderBlock::updateFirstLetter()
{
RenderObject* firstLetterObj;
RenderElement* firstLetterContainer;
getFirstLetter(firstLetterObj, firstLetterContainer);
if (!firstLetterObj)
return;
if (firstLetterObj->parent()->style().styleType() == FIRST_LETTER) {
updateFirstLetterStyle(firstLetterContainer, firstLetterObj);
return;
}
if (!firstLetterObj->isText())
return;
LayoutStateDisabler layoutStateDisabler(&view());
createFirstLetterRenderer(firstLetterContainer, toRenderText(firstLetterObj));
}
LayoutUnit RenderBlock::paginationStrut() const
{
RenderBlockRareData* rareData = getRareData(this);
return rareData ? rareData->m_paginationStrut : LayoutUnit();
}
LayoutUnit RenderBlock::pageLogicalOffset() const
{
RenderBlockRareData* rareData = getRareData(this);
return rareData ? rareData->m_pageLogicalOffset : LayoutUnit();
}
void RenderBlock::setPaginationStrut(LayoutUnit strut)
{
RenderBlockRareData* rareData = getRareData(this);
if (!rareData) {
if (!strut)
return;
rareData = &ensureRareData(this);
}
rareData->m_paginationStrut = strut;
}
void RenderBlock::setPageLogicalOffset(LayoutUnit logicalOffset)
{
RenderBlockRareData* rareData = getRareData(this);
if (!rareData) {
if (!logicalOffset)
return;
rareData = &ensureRareData(this);
}
rareData->m_pageLogicalOffset = logicalOffset;
}
void RenderBlock::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
{
if (isAnonymousBlockContinuation()) {
rects.append(pixelSnappedIntRect(accumulatedOffset.x(), accumulatedOffset.y() - collapsedMarginBefore(),
width(), height() + collapsedMarginBefore() + collapsedMarginAfter()));
continuation()->absoluteRects(rects, accumulatedOffset - toLayoutSize(location() +
inlineElementContinuation()->containingBlock()->location()));
} else
rects.append(pixelSnappedIntRect(accumulatedOffset, size()));
}
void RenderBlock::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
{
FloatRect localRect = isAnonymousBlockContinuation()
? FloatRect(0, -collapsedMarginBefore(), width(), height() + collapsedMarginBefore() + collapsedMarginAfter())
: FloatRect(0, 0, width(), height());
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (!flowThread || !flowThread->absoluteQuadsForBox(quads, wasFixed, this, localRect.y(), localRect.maxY()))
quads.append(localToAbsoluteQuad(localRect, 0 , wasFixed));
if (isAnonymousBlockContinuation())
continuation()->absoluteQuads(quads, wasFixed);
}
LayoutRect RenderBlock::rectWithOutlineForRepaint(const RenderLayerModelObject* repaintContainer, LayoutUnit outlineWidth) const
{
LayoutRect r(RenderBox::rectWithOutlineForRepaint(repaintContainer, outlineWidth));
if (isAnonymousBlockContinuation())
r.inflateY(collapsedMarginBefore()); return r;
}
RenderElement* RenderBlock::hoverAncestor() const
{
return isAnonymousBlockContinuation() ? continuation() : RenderBox::hoverAncestor();
}
void RenderBlock::updateDragState(bool dragOn)
{
RenderBox::updateDragState(dragOn);
if (RenderBoxModelObject* continuation = this->continuation())
continuation->updateDragState(dragOn);
}
const RenderStyle& RenderBlock::outlineStyleForRepaint() const
{
return isAnonymousBlockContinuation() ? continuation()->style() : style();
}
void RenderBlock::childBecameNonInline(RenderObject*)
{
makeChildrenNonInline();
if (isAnonymousBlock() && parent() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
}
void RenderBlock::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
{
if (result.innerNode())
return;
if (Node* n = nodeForHitTest()) {
result.setInnerNode(n);
if (!result.innerNonSharedNode())
result.setInnerNonSharedNode(n);
result.setLocalPoint(point);
}
}
LayoutRect RenderBlock::localCaretRect(InlineBox* inlineBox, int caretOffset, LayoutUnit* extraWidthToEndOfLine)
{
if (firstChild())
return RenderBox::localCaretRect(inlineBox, caretOffset, extraWidthToEndOfLine);
LayoutRect caretRect = localCaretRectForEmptyElement(width(), textIndentOffset());
if (extraWidthToEndOfLine)
*extraWidthToEndOfLine = width() - caretRect.maxX();
return caretRect;
}
void RenderBlock::addFocusRingRectsForInlineChildren(Vector<IntRect>&, const LayoutPoint&, const RenderLayerModelObject*)
{
ASSERT_NOT_REACHED();
}
void RenderBlock::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer)
{
if (inlineElementContinuation()) {
bool nextInlineHasLineBox = inlineElementContinuation()->firstLineBox();
bool prevInlineHasLineBox = toRenderInline(inlineElementContinuation()->element()->renderer())->firstLineBox();
float topMargin = prevInlineHasLineBox ? collapsedMarginBefore() : LayoutUnit();
float bottomMargin = nextInlineHasLineBox ? collapsedMarginAfter() : LayoutUnit();
LayoutRect rect(additionalOffset.x(), additionalOffset.y() - topMargin, width(), height() + topMargin + bottomMargin);
if (!rect.isEmpty())
rects.append(pixelSnappedIntRect(rect));
} else if (width() && height())
rects.append(pixelSnappedIntRect(additionalOffset, size()));
if (!hasOverflowClip() && !hasControlClip()) {
if (childrenInline())
addFocusRingRectsForInlineChildren(rects, additionalOffset, paintContainer);
for (RenderObject* curr = firstChild(); curr; curr = curr->nextSibling()) {
if (!curr->isText() && !curr->isListMarker() && curr->isBox()) {
RenderBox* box = toRenderBox(curr);
FloatPoint pos;
if (box->layer())
pos = curr->localToContainerPoint(FloatPoint(), paintContainer);
else
pos = FloatPoint(additionalOffset.x() + box->x(), additionalOffset.y() + box->y());
box->addFocusRingRects(rects, flooredLayoutPoint(pos), paintContainer);
}
}
}
if (inlineElementContinuation())
inlineElementContinuation()->addFocusRingRects(rects, flooredLayoutPoint(LayoutPoint(additionalOffset + inlineElementContinuation()->containingBlock()->location() - location())), paintContainer);
}
RenderBox* RenderBlock::createAnonymousBoxWithSameTypeAs(const RenderObject* parent) const
{
return createAnonymousWithParentRendererAndDisplay(parent, style().display());
}
LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
{
LayoutState* layoutState = view().layoutState();
if (layoutState && !layoutState->isPaginated())
return 0;
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (flowThread)
return flowThread->offsetFromLogicalTopOfFirstRegion(this);
if (layoutState) {
ASSERT(layoutState->m_renderer == this);
LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
}
ASSERT_NOT_REACHED();
return 0;
}
RenderRegion* RenderBlock::regionAtBlockOffset(LayoutUnit blockOffset) const
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (!flowThread || !flowThread->hasValidRegionInfo())
return 0;
return flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstPage() + blockOffset, true);
}
static bool canComputeRegionRangeForBox(const RenderBlock* parentBlock, const RenderBox& childBox, const RenderFlowThread* flowThreadContainingBlock)
{
ASSERT(parentBlock);
ASSERT(!childBox.isRenderFlowThread());
if (!flowThreadContainingBlock)
return false;
if (!flowThreadContainingBlock->hasRegions())
return false;
if (!childBox.canHaveOutsideRegionRange())
return false;
return flowThreadContainingBlock->hasCachedRegionRangeForBox(parentBlock);
}
bool RenderBlock::childBoxIsUnsplittableForFragmentation(const RenderBox& child) const
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
bool checkColumnBreaks = flowThread && flowThread->shouldCheckColumnBreaks();
bool checkPageBreaks = !checkColumnBreaks && view().layoutState()->m_pageLogicalHeight;
bool checkRegionBreaks = flowThread && flowThread->isRenderNamedFlowThread();
return child.isUnsplittableForPagination() || (checkColumnBreaks && child.style().columnBreakInside() == PBAVOID)
|| (checkPageBreaks && child.style().pageBreakInside() == PBAVOID)
|| (checkRegionBreaks && child.style().regionBreakInside() == PBAVOID);
}
void RenderBlock::computeRegionRangeForBoxChild(const RenderBox& box) const
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
ASSERT(canComputeRegionRangeForBox(this, box, flowThread));
RenderRegion* startRegion;
RenderRegion* endRegion;
LayoutUnit offsetFromLogicalTopOfFirstRegion = box.offsetFromLogicalTopOfFirstPage();
if (childBoxIsUnsplittableForFragmentation(box))
startRegion = endRegion = flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstRegion, true);
else {
startRegion = flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstRegion, true);
endRegion = flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstRegion + logicalHeightForChild(box), true);
}
flowThread->setRegionRangeForBox(&box, startRegion, endRegion);
}
void RenderBlock::estimateRegionRangeForBoxChild(const RenderBox& box) const
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (!canComputeRegionRangeForBox(this, box, flowThread))
return;
if (childBoxIsUnsplittableForFragmentation(box)) {
computeRegionRangeForBoxChild(box);
return;
}
LogicalExtentComputedValues estimatedValues;
box.computeLogicalHeight(RenderFlowThread::maxLogicalHeight(), logicalTopForChild(box), estimatedValues);
LayoutUnit offsetFromLogicalTopOfFirstRegion = box.offsetFromLogicalTopOfFirstPage();
RenderRegion* startRegion = flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstRegion, true);
RenderRegion* endRegion = flowThread->regionAtBlockOffset(this, offsetFromLogicalTopOfFirstRegion + estimatedValues.m_extent, true);
flowThread->setRegionRangeForBox(&box, startRegion, endRegion);
}
bool RenderBlock::updateRegionRangeForBoxChild(const RenderBox& box) const
{
RenderFlowThread* flowThread = flowThreadContainingBlock();
if (!canComputeRegionRangeForBox(this, box, flowThread))
return false;
RenderRegion* startRegion = nullptr;
RenderRegion* endRegion = nullptr;
flowThread->getRegionRangeForBox(&box, startRegion, endRegion);
computeRegionRangeForBoxChild(box);
RenderRegion* newStartRegion = nullptr;
RenderRegion* newEndRegion = nullptr;
flowThread->getRegionRangeForBox(&box, newStartRegion, newEndRegion);
if (newStartRegion != startRegion)
return true;
if (box.needsLayoutAfterRegionRangeChange() && newEndRegion != endRegion)
return true;
return false;
}
LayoutUnit RenderBlock::collapsedMarginBeforeForChild(const RenderBox& child) const
{
if (!child.isWritingModeRoot())
return child.collapsedMarginBefore();
if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
return child.collapsedMarginAfter();
return marginBeforeForChild(child);
}
LayoutUnit RenderBlock::collapsedMarginAfterForChild(const RenderBox& child) const
{
if (!child.isWritingModeRoot())
return child.collapsedMarginAfter();
if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
return child.collapsedMarginBefore();
return marginAfterForChild(child);
}
bool RenderBlock::hasMarginBeforeQuirk(const RenderBox& child) const
{
if (!child.isWritingModeRoot())
return child.isRenderBlock() ? toRenderBlock(child).hasMarginBeforeQuirk() : child.style().hasMarginBeforeQuirk();
if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
return child.isRenderBlock() ? toRenderBlock(child).hasMarginAfterQuirk() : child.style().hasMarginAfterQuirk();
return false;
}
bool RenderBlock::hasMarginAfterQuirk(const RenderBox& child) const
{
if (!child.isWritingModeRoot())
return child.isRenderBlock() ? toRenderBlock(child).hasMarginAfterQuirk() : child.style().hasMarginAfterQuirk();
if (child.isHorizontalWritingMode() == isHorizontalWritingMode())
return child.isRenderBlock() ? toRenderBlock(child).hasMarginBeforeQuirk() : child.style().hasMarginBeforeQuirk();
return false;
}
const char* RenderBlock::renderName() const
{
if (isBody())
return "RenderBody";
if (isFloating())
return "RenderBlock (floating)";
if (isOutOfFlowPositioned())
return "RenderBlock (positioned)";
if (isAnonymousBlock())
return "RenderBlock (anonymous)";
if (isPseudoElement())
return "RenderBlock (generated)";
if (isAnonymous())
return "RenderBlock (generated)";
if (isRelPositioned())
return "RenderBlock (relative positioned)";
if (isStickyPositioned())
return "RenderBlock (sticky positioned)";
return "RenderBlock";
}
template <typename CharacterType>
static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, const RenderStyle& style, TextRun::ExpansionBehavior expansion)
{
TextDirection textDirection = LTR;
bool directionalOverride = style.rtlOrdering() == VisualOrder;
TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
if (font.primaryFont()->isSVGFont()) {
ASSERT(context); run.setRenderingContext(SVGTextRunRenderingContext::create(*context));
}
return run;
}
template <typename CharacterType>
static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, const RenderStyle& style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
{
TextDirection textDirection = LTR;
bool directionalOverride = style.rtlOrdering() == VisualOrder;
if (flags != DefaultTextRunFlags) {
if (flags & RespectDirection)
textDirection = style.direction();
if (flags & RespectDirectionOverride)
directionalOverride |= isOverride(style.unicodeBidi());
}
TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
if (font.primaryFont()->isSVGFont()) {
ASSERT(context); run.setRenderingContext(SVGTextRunRenderingContext::create(*context));
}
return run;
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, const RenderStyle& style, TextRun::ExpansionBehavior expansion)
{
return constructTextRunInternal(context, font, characters, length, style, expansion);
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, const RenderStyle& style, TextRun::ExpansionBehavior expansion)
{
return constructTextRunInternal(context, font, characters, length, style, expansion);
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, const RenderStyle& style, TextRun::ExpansionBehavior expansion)
{
if (text->is8Bit())
return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, expansion);
return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, expansion);
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, const RenderStyle& style, TextRun::ExpansionBehavior expansion)
{
ASSERT(offset + length <= text->textLength());
if (text->is8Bit())
return constructTextRunInternal(context, font, text->characters8() + offset, length, style, expansion);
return constructTextRunInternal(context, font, text->characters16() + offset, length, style, expansion);
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const String& string, const RenderStyle& style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
{
unsigned length = string.length();
if (!length || string.is8Bit())
return constructTextRunInternal(context, font, string.characters8(), length, style, expansion, flags);
return constructTextRunInternal(context, font, string.characters16(), length, style, expansion, flags);
}
RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const RenderObject* parent, EDisplay display)
{
RenderBlock* newBox;
if (display == FLEX || display == INLINE_FLEX)
newBox = new RenderFlexibleBox(parent->document(), RenderStyle::createAnonymousStyleWithDisplay(&parent->style(), FLEX));
else
newBox = new RenderBlockFlow(parent->document(), RenderStyle::createAnonymousStyleWithDisplay(&parent->style(), BLOCK));
newBox->initializeStyle();
return newBox;
}
#ifndef NDEBUG
void RenderBlock::checkPositionedObjectsNeedLayout()
{
if (!gPositionedDescendantsMap)
return;
TrackedRendererListHashSet* positionedDescendantSet = positionedObjects();
if (!positionedDescendantSet)
return;
for (auto it = positionedDescendantSet->begin(), end = positionedDescendantSet->end(); it != end; ++it) {
RenderBox* currBox = *it;
ASSERT(!currBox->needsLayout());
}
}
void RenderBlock::showLineTreeAndMark(const InlineBox*, const char*, const InlineBox*, const char*, const RenderObject*) const
{
showRenderObject();
}
#endif
}