#include "config.h"
#include "RenderBlock.h"
#include "ColumnInfo.h"
#include "Document.h"
#include "Element.h"
#include "FloatQuad.h"
#include "Frame.h"
#include "FrameSelection.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLFormElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "InlineIterator.h"
#include "InlineTextBox.h"
#include "LayoutRepainter.h"
#include "OverflowEvent.h"
#include "PODFreeListArena.h"
#include "Page.h"
#include "PaintInfo.h"
#include "RenderBoxRegionInfo.h"
#include "RenderCombineText.h"
#include "RenderDeprecatedFlexibleBox.h"
#include "RenderImage.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderMarquee.h"
#include "RenderNamedFlowThread.h"
#include "RenderRegion.h"
#include "RenderReplica.h"
#include "RenderTableCell.h"
#include "RenderTextFragment.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "Settings.h"
#include "SVGTextRunRenderingContext.h"
#include "TransformState.h"
#include <wtf/StdLibExtras.h>
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
using namespace HTMLNames;
struct SameSizeAsFloatingObject {
void* pointers[2];
LayoutRect rect;
int paginationStrut;
uint32_t bitfields : 8;
};
COMPILE_ASSERT(sizeof(RenderBlock::MarginValues) == sizeof(LayoutUnit[4]), MarginValues_should_stay_small);
struct SameSizeAsMarginInfo {
uint32_t bitfields : 16;
LayoutUnit margins[2];
};
typedef WTF::HashMap<const RenderBox*, ColumnInfo*> ColumnInfoMap;
static ColumnInfoMap* gColumnInfoMap = 0;
static TrackedDescendantsMap* gPositionedDescendantsMap = 0;
static TrackedDescendantsMap* gPercentHeightDescendantsMap = 0;
static TrackedContainerMap* gPositionedContainerMap = 0;
static TrackedContainerMap* gPercentHeightContainerMap = 0;
typedef WTF::HashMap<RenderBlock*, ListHashSet<RenderInline*>*> ContinuationOutlineTableMap;
typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
static int gDelayUpdateScrollInfo = 0;
static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
static inline bool canHaveGeneratedChildren(RenderObject* renderer)
{
return (renderer->canHaveChildren()
&& (!renderer->isDeprecatedFlexibleBox()
|| static_cast<RenderDeprecatedFlexibleBox*>(renderer)->canHaveGeneratedChildren()));
}
bool RenderBlock::s_canPropagateFloatIntoSibling = false;
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) {
if (FrameView* frameView = m_block->document()->view())
frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
}
}
private:
const RenderBlock* m_block;
bool m_shouldDispatchEvent;
bool m_hadHorizontalLayoutOverflow;
bool m_hadVerticalLayoutOverflow;
};
RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, LayoutUnit beforeBorderPadding, LayoutUnit afterBorderPadding)
: m_atBeforeSideOfBlock(true)
, m_atAfterSideOfBlock(false)
, m_marginBeforeQuirk(false)
, m_marginAfterQuirk(false)
, m_determinedMarginBeforeQuirk(false)
{
RenderStyle* blockStyle = block->style();
m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isOutOfFlowPositioned()
&& !block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable()
&& !block->isWritingModeRoot() && blockStyle->hasAutoColumnCount() && blockStyle->hasAutoColumnWidth()
&& !blockStyle->columnSpan();
m_canCollapseMarginBeforeWithChildren = m_canCollapseWithChildren && !beforeBorderPadding && blockStyle->marginBeforeCollapse() != MSEPARATE;
m_canCollapseMarginAfterWithChildren = m_canCollapseWithChildren && (afterBorderPadding == 0) &&
(blockStyle->logicalHeight().isAuto() && !blockStyle->logicalHeight().value()) && blockStyle->marginAfterCollapse() != MSEPARATE;
m_quirkContainer = block->isTableCell() || block->isBody() || blockStyle->marginBeforeCollapse() == MDISCARD
|| blockStyle->marginAfterCollapse() == MDISCARD;
m_positiveMargin = m_canCollapseMarginBeforeWithChildren ? block->maxPositiveMarginBefore() : ZERO_LAYOUT_UNIT;
m_negativeMargin = m_canCollapseMarginBeforeWithChildren ? block->maxNegativeMarginBefore() : ZERO_LAYOUT_UNIT;
}
RenderBlock::RenderBlock(Node* node)
: RenderBox(node)
, m_lineHeight(-1)
, m_beingDestroyed(false)
, m_hasMarkupTruncation(false)
, m_widthForTextAutosizing(-1)
, m_lineCountForTextAutosizing(NOT_SET)
{
setChildrenInline(true);
COMPILE_ASSERT(sizeof(RenderBlock::FloatingObject) == sizeof(SameSizeAsFloatingObject), FloatingObject_should_stay_small);
COMPILE_ASSERT(sizeof(RenderBlock::MarginInfo) == sizeof(SameSizeAsMarginInfo), MarginInfo_should_stay_small);
}
static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, TrackedDescendantsMap*& descendantMap, TrackedContainerMap*& containerMap)
{
if (TrackedRendererListHashSet* descendantSet = descendantMap->take(block)) {
TrackedRendererListHashSet::iterator end = descendantSet->end();
for (TrackedRendererListHashSet::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
HashSet<RenderBlock*>* containerSet = containerMap->get(*descendant);
ASSERT(containerSet);
if (!containerSet)
continue;
ASSERT(containerSet->contains(block));
containerSet->remove(block);
if (containerSet->isEmpty()) {
containerMap->remove(*descendant);
delete containerSet;
}
}
delete descendantSet;
}
}
RenderBlock::~RenderBlock()
{
if (m_floatingObjects)
deleteAllValues(m_floatingObjects->set());
if (hasColumns())
delete gColumnInfoMap->take(this);
if (gPercentHeightDescendantsMap)
removeBlockFromDescendantAndContainerMaps(this, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
if (gPositionedDescendantsMap)
removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
}
void RenderBlock::willBeDestroyed()
{
m_beingDestroyed = true;
children()->destroyLeftoverChildren();
RenderBoxModelObject* continuation = this->continuation();
if (continuation) {
continuation->destroy();
setContinuation(0);
}
if (!documentBeingDestroyed()) {
if (firstLineBox()) {
if (isSelectionBorder())
view()->clearSelection();
if (isAnonymousBlock()) {
for (InlineFlowBox* box = firstLineBox(); box; box = box->nextLineBox()) {
while (InlineBox* childBox = box->firstChild())
childBox->remove();
}
}
} else if (parent())
parent()->dirtyLinesFromChangedChild(this);
}
m_lineBoxes.deleteLineBoxes(renderArena());
if (lineGridBox())
lineGridBox()->destroy(renderArena());
if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
gDelayedUpdateScrollInfoSet->remove(this);
RenderBox::willBeDestroyed();
}
void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
{
RenderStyle* oldStyle = style();
s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
setReplaced(newStyle->isDisplayInlineType());
if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()) {
if (newStyle->position() == StaticPosition)
removePositionedObjects(0);
else if (oldStyle->position() == StaticPosition) {
RenderObject* 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);
}
if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
markAllDescendantsWithFloatsForLayout();
}
RenderBox::styleWillChange(diff, newStyle);
}
void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
if (!isAnonymousBlock()) {
for (RenderBlock* currCont = blockElementContinuation(); currCont; currCont = currCont->blockElementContinuation()) {
RenderBoxModelObject* nextCont = currCont->continuation();
currCont->setContinuation(0);
currCont->setStyle(style());
currCont->setContinuation(nextCont);
}
}
propagateStyleToAnonymousChildren(true);
m_lineHeight = -1;
if (!isAnonymous() && document()->usesBeforeAfterRules() && canHaveGeneratedChildren(this)) {
updateBeforeAfterContent(BEFORE);
updateBeforeAfterContent(AFTER);
}
bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
RenderBlock* parentBlock = this;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
if (curr->isRenderBlock()) {
RenderBlock* currBlock = toRenderBlock(curr);
if (currBlock->hasOverhangingFloats()) {
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
RenderBox* renderer = (*it)->renderer();
if (currBlock->hasOverhangingFloat(renderer)) {
parentBlock = currBlock;
break;
}
}
}
}
}
parentBlock->markAllDescendantsWithFloatsForLayout();
parentBlock->markSiblingsWithFloatsForLayout();
}
}
void RenderBlock::updateBeforeAfterContent(PseudoId pseudoId)
{
if (parent() && parent()->createsAnonymousWrapper())
return;
children()->updateBeforeAfterContent(this, pseudoId);
}
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()->isAnonymousColumnSpanBlock() || 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);
}
void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
{
ASSERT(!continuation());
RenderBlock* beforeChildParent = 0;
if (beforeChild) {
RenderObject* curr = beforeChild;
while (curr && curr->parent() != this)
curr = curr->parent();
beforeChildParent = toRenderBlock(curr);
ASSERT(beforeChildParent);
ASSERT(beforeChildParent->isAnonymousColumnsBlock() || beforeChildParent->isAnonymousColumnSpanBlock());
} else
beforeChildParent = toRenderBlock(lastChild());
if (newChild->isFloatingOrOutOfFlowPositioned()) {
beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
return;
}
bool newChildHasColumnSpan = newChild->style()->columnSpan() && !newChild->isInline();
bool beforeChildParentHoldsColumnSpans = beforeChildParent->isAnonymousColumnSpanBlock();
if (newChildHasColumnSpan == beforeChildParentHoldsColumnSpans) {
beforeChildParent->addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
return;
}
if (!beforeChild) {
RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
children()->appendChildNode(this, newBox);
newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
return;
}
RenderObject* immediateChild = beforeChild;
bool isPreviousBlockViable = true;
while (immediateChild->parent() != this) {
if (isPreviousBlockViable)
isPreviousBlockViable = !immediateChild->previousSibling();
immediateChild = immediateChild->parent();
}
if (isPreviousBlockViable && immediateChild->previousSibling()) {
toRenderBlock(immediateChild->previousSibling())->addChildIgnoringAnonymousColumnBlocks(newChild, 0); return;
}
RenderObject* newBeforeChild = splitAnonymousBoxesAroundChild(beforeChild);
RenderBlock* newBox = newChildHasColumnSpan ? createAnonymousColumnSpanBlock() : createAnonymousColumnsBlock();
children()->insertChildNode(this, newBox, newBeforeChild);
newBox->addChildIgnoringAnonymousColumnBlocks(newChild, 0);
return;
}
RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
{
RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
for (RenderObject* curr = this; curr; curr = curr->parent()) {
if (!curr->isRenderBlock() || curr->isFloatingOrOutOfFlowPositioned() || curr->isTableCell() || curr->isRoot() || curr->isRenderView() || curr->hasOverflowClip()
|| curr->isInlineBlockOrInlineTable())
return 0;
if (curr->isTable())
return 0;
RenderBlock* currBlock = toRenderBlock(curr);
if (!currBlock->createsAnonymousWrapper())
firstChildIgnoringAnonymousWrappers = currBlock;
if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
return firstChildIgnoringAnonymousWrappers;
if (currBlock->isAnonymousColumnSpanBlock())
return 0;
}
return 0;
}
RenderBlock* RenderBlock::clone() const
{
RenderBlock* cloneBlock;
if (isAnonymousBlock()) {
cloneBlock = createAnonymousBlock();
cloneBlock->setChildrenInline(childrenInline());
}
else {
RenderObject* cloneRenderer = node()->createRenderer(renderArena(), style());
cloneBlock = toRenderBlock(cloneRenderer);
cloneBlock->setStyle(style());
cloneBlock->setChildrenInline(cloneBlock->firstChild() ? cloneBlock->firstChild()->isInline() : childrenInline());
}
return cloneBlock;
}
void RenderBlock::splitBlocks(RenderBlock* fromBlock, RenderBlock* toBlock,
RenderBlock* middleBlock,
RenderObject* beforeChild, RenderBoxModelObject* oldCont)
{
RenderBlock* cloneBlock = clone();
if (!isAnonymousBlock())
cloneBlock->setContinuation(oldCont);
if (!beforeChild && isAfterContent(lastChild()))
beforeChild = lastChild();
if (beforeChild && childrenInline())
deleteLineBoxTree();
moveChildrenTo(cloneBlock, beforeChild, 0, true);
if (!cloneBlock->isAnonymousBlock())
middleBlock->setContinuation(cloneBlock);
RenderBoxModelObject* curr = toRenderBoxModelObject(parent());
RenderBoxModelObject* currChild = this;
RenderObject* currChildNextSibling = currChild->nextSibling();
bool documentUsesBeforeAfterRules = document()->usesBeforeAfterRules();
while (curr && curr != fromBlock) {
ASSERT(curr->isRenderBlock());
RenderBlock* blockCurr = toRenderBlock(curr);
RenderBlock* cloneChild = cloneBlock;
cloneBlock = blockCurr->clone();
cloneBlock->addChildIgnoringContinuation(cloneChild, 0);
if (!blockCurr->isAnonymousBlock()) {
oldCont = blockCurr->continuation();
blockCurr->setContinuation(cloneBlock);
cloneBlock->setContinuation(oldCont);
}
bool isLastChild = (currChildNextSibling == blockCurr->lastChild());
if (documentUsesBeforeAfterRules)
blockCurr->children()->updateBeforeAfterContent(blockCurr, AFTER);
if (isLastChild && currChildNextSibling != blockCurr->lastChild())
currChildNextSibling = 0;
blockCurr->moveChildrenTo(cloneBlock, currChildNextSibling, 0, true);
currChild = curr;
currChildNextSibling = currChild->nextSibling();
curr = toRenderBoxModelObject(curr->parent());
}
toBlock->children()->appendChildNode(toBlock, cloneBlock);
fromBlock->moveChildrenTo(toBlock, currChildNextSibling, 0, true);
}
void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
RenderObject* newChild, RenderBoxModelObject* oldCont)
{
RenderBlock* pre = 0;
RenderBlock* block = containingColumnsBlock();
block->deleteLineBoxTree();
bool madeNewBeforeBlock = false;
if (block->isAnonymousColumnsBlock()) {
pre = block;
pre->removePositionedObjects(0);
block = toRenderBlock(block->parent());
} else {
pre = block->createAnonymousColumnsBlock();
pre->setChildrenInline(false);
madeNewBeforeBlock = true;
}
RenderBlock* post = block->createAnonymousColumnsBlock();
post->setChildrenInline(false);
RenderObject* boxFirst = madeNewBeforeBlock ? block->firstChild() : pre->nextSibling();
if (madeNewBeforeBlock)
block->children()->insertChildNode(block, pre, boxFirst);
block->children()->insertChildNode(block, newBlockBox, boxFirst);
block->children()->insertChildNode(block, post, boxFirst);
block->setChildrenInline(false);
if (madeNewBeforeBlock)
block->moveChildrenTo(pre, boxFirst, 0, true);
splitBlocks(pre, post, newBlockBox, beforeChild, oldCont);
newBlockBox->setChildrenInline(false);
newBlockBox->addChild(newChild);
pre->setNeedsLayoutAndPrefWidthsRecalc();
block->setNeedsLayoutAndPrefWidthsRecalc();
post->setNeedsLayoutAndPrefWidthsRecalc();
}
void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
{
RenderBlock* pre = 0;
RenderBlock* post = 0;
RenderBlock* block = this;
block->deleteLineBoxTree();
if (beforeChild && beforeChild->parent() != this)
beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
if (beforeChild != firstChild()) {
pre = block->createAnonymousColumnsBlock();
pre->setChildrenInline(block->childrenInline());
}
if (beforeChild) {
post = block->createAnonymousColumnsBlock();
post->setChildrenInline(block->childrenInline());
}
RenderObject* boxFirst = block->firstChild();
if (pre)
block->children()->insertChildNode(block, pre, boxFirst);
block->children()->insertChildNode(block, newBlockBox, boxFirst);
if (post)
block->children()->insertChildNode(block, post, boxFirst);
block->setChildrenInline(false);
block->moveChildrenTo(pre, boxFirst, beforeChild, true);
block->moveChildrenTo(post, beforeChild, 0, true);
newBlockBox->setChildrenInline(false);
newBlockBox->addChild(newChild);
if (pre)
pre->setNeedsLayoutAndPrefWidthsRecalc();
block->setNeedsLayoutAndPrefWidthsRecalc();
if (post)
post->setNeedsLayoutAndPrefWidthsRecalc();
}
RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
{
RenderBlock* columnsBlockAncestor = 0;
if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
&& !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
columnsBlockAncestor = containingColumnsBlock(false);
if (columnsBlockAncestor) {
RenderObject* curr = this;
while (curr && curr != columnsBlockAncestor) {
if (curr->isRenderBlock() && toRenderBlock(curr)->continuation()) {
columnsBlockAncestor = 0;
break;
}
curr = curr->parent();
}
}
}
return columnsBlockAncestor;
}
void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild, RenderObject* beforeChild)
{
if (!beforeChild)
beforeChild = afterPseudoElementRenderer();
if (beforeChild && beforeChild->parent() != this) {
RenderObject* beforeChildContainer = beforeChild->parent();
while (beforeChildContainer->parent() != this)
beforeChildContainer = beforeChildContainer->parent();
ASSERT(beforeChildContainer);
if (beforeChildContainer->isAnonymous()) {
RenderObject* 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;
}
} else {
ASSERT(beforeChild->isRunIn());
beforeChild = beforeChildContainer;
}
}
if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
beforeChild = beforeChild->nextSibling();
RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
if (columnsBlockAncestor) {
RenderBlock* newBox = createAnonymousColumnSpanBlock();
if (columnsBlockAncestor != this) {
RenderBoxModelObject* oldContinuation = continuation();
if (!isAnonymousBlock())
setContinuation(newBox);
bool isFirstChild = (beforeChild == firstChild());
bool isLastChild = (beforeChild == lastChild());
if (document()->usesBeforeAfterRules())
children()->updateBeforeAfterContent(this, AFTER);
if (isLastChild && beforeChild != lastChild()) {
beforeChild = 0;
} else if (isFirstChild && beforeChild != firstChild()) {
beforeChild = firstChild();
}
splitFlow(beforeChild, newBox, newChild, oldContinuation);
return;
}
makeChildrenAnonymousColumnBlocks(beforeChild, newBox, newChild);
return;
}
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()) {
afterChild->addChild(newChild);
return;
}
if (newChild->isInline()) {
RenderBlock* newBox = createAnonymousBlock();
RenderBox::addChild(newBox, beforeChild);
newBox->addChild(newChild);
return;
}
}
RenderBox::addChild(newChild, beforeChild);
placeRunInIfNeeded(newChild, DoNotPlaceGeneratedRunIn);
if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
}
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 (!isAnonymousBlock() && firstChild() && (firstChild()->isAnonymousColumnsBlock() || firstChild()->isAnonymousColumnSpanBlock()))
addChildToAnonymousColumnBlocks(newChild, beforeChild);
else
addChildIgnoringAnonymousColumnBlocks(newChild, beforeChild);
}
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::deleteLineBoxTree()
{
if (containsFloats()) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
ASSERT(!((*it)->m_originatingLine) || (*it)->m_originatingLine->renderer() == this);
(*it)->m_originatingLine = 0;
}
}
m_lineBoxes.deleteLineBoxTree(renderArena());
}
RootInlineBox* RenderBlock::createRootInlineBox()
{
return new (renderArena()) RootInlineBox(this);
}
RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
{
RootInlineBox* rootBox = createRootInlineBox();
m_lineBoxes.appendLineBox(rootBox);
return rootBox;
}
void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
{
ASSERT(isInlineBlockOrInlineTable() || !isInline());
ASSERT(!insertionPoint || insertionPoint->parent() == this);
setChildrenInline(false);
RenderObject *child = firstChild();
if (!child)
return;
deleteLineBoxTree();
if (child->isRunIn()) {
moveRunInToOriginalPosition(child);
child = firstChild();
}
while (child) {
RenderObject *inlineRunStart, *inlineRunEnd;
getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
if (!inlineRunStart)
break;
child = inlineRunEnd->nextSibling();
RenderBlock* block = createAnonymousBlock();
children()->insertChildNode(this, block, inlineRunStart);
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() || (child->firstChild() && (child->isAnonymousColumnSpanBlock() || child->isAnonymousColumnsBlock())))
return;
RenderObject* firstAnChild = child->m_children.firstChild();
RenderObject* lastAnChild = child->m_children.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 == m_children.firstChild())
m_children.setFirstChild(firstAnChild);
if (child == m_children.lastChild())
m_children.setLastChild(lastAnChild);
} else {
if (child == m_children.firstChild())
m_children.setFirstChild(child->nextSibling());
if (child == m_children.lastChild())
m_children.setLastChild(child->previousSibling());
if (child->previousSibling())
child->previousSibling()->setNextSibling(child->nextSibling());
if (child->nextSibling())
child->nextSibling()->setPreviousSibling(child->previousSibling());
}
child->setParent(0);
child->setPreviousSibling(0);
child->setNextSibling(0);
child->children()->setFirstChild(0);
child->m_next = 0;
child->destroy();
}
static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObject* prev, RenderObject* next)
{
if (oldChild->documentBeingDestroyed() || oldChild->isInline() || oldChild->virtualContinuation())
return false;
if ((prev && (!prev->isAnonymousBlock() || toRenderBlock(prev)->continuation() || toRenderBlock(prev)->beingDestroyed()))
|| (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
return false;
if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
return false;
if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
return false;
if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
|| (next && (next->isRubyRun() || next->isRubyBase())))
return false;
if (!prev || !next)
return true;
return prev->isAnonymousColumnsBlock() == next->isAnonymousColumnsBlock()
&& prev->isAnonymousColumnSpanBlock() == next->isAnonymousColumnSpanBlock();
}
void RenderBlock::collapseAnonymousBoxChild(RenderBlock* parent, RenderObject* child)
{
parent->setNeedsLayoutAndPrefWidthsRecalc();
parent->setChildrenInline(child->childrenInline());
RenderObject* nextSibling = child->nextSibling();
RenderFlowThread* childFlowThread = child->enclosingRenderFlowThread();
RenderBlock* anonBlock = toRenderBlock(parent->children()->removeChildNode(parent, child, child->hasLayer()));
anonBlock->moveAllChildrenTo(parent, nextSibling, child->hasLayer());
anonBlock->deleteLineBoxTree();
if (childFlowThread && childFlowThread->isRenderNamedFlowThread())
toRenderNamedFlowThread(childFlowThread)->removeFlowChildInfo(anonBlock);
anonBlock->destroy();
}
void RenderBlock::removeChild(RenderObject* oldChild)
{
if (documentBeingDestroyed()) {
RenderBox::removeChild(oldChild);
return;
}
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());
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(style(), BLOCK);
bool inlineChildrenBlockHasLayer = inlineChildrenBlock->hasLayer();
inlineChildrenBlock->setStyle(newStyle);
children()->removeChildNode(this, inlineChildrenBlock, inlineChildrenBlockHasLayer);
blockChildrenBlock->children()->insertChildNode(blockChildrenBlock, inlineChildrenBlock, prev == inlineChildrenBlock ? blockChildrenBlock->firstChild() : 0,
inlineChildrenBlockHasLayer || blockChildrenBlock->hasLayer());
next->setNeedsLayoutAndPrefWidthsRecalc();
if (inlineChildrenBlock == prevBlock)
prev = 0;
else
next = 0;
} else {
nextBlock->moveAllChildrenTo(prevBlock, nextBlock->hasLayer() || prevBlock->hasLayer());
nextBlock->deleteLineBoxTree();
nextBlock->destroy();
next = 0;
}
}
RenderBox::removeChild(oldChild);
RenderObject* child = prev ? prev : next;
if (canMergeAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && !isFlexibleBoxIncludingDeprecated()) {
collapseAnonymousBoxChild(this, child);
} else if (((prev && prev->isAnonymousBlock()) || (next && next->isAnonymousBlock())) && !isFlexibleBoxIncludingDeprecated()) {
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);
}
}
if (!firstChild()) {
if (childrenInline())
deleteLineBoxTree();
}
}
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 !firstLineBox();
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (child->isFloatingOrOutOfFlowPositioned())
continue;
if (!child->isSelfCollapsingBlock())
return false;
}
return true;
}
return false;
}
void RenderBlock::startDelayUpdateScrollInfo()
{
if (gDelayUpdateScrollInfo == 0) {
ASSERT(!gDelayedUpdateScrollInfoSet);
gDelayedUpdateScrollInfoSet = new DelayedUpdateScrollInfoSet;
}
ASSERT(gDelayedUpdateScrollInfoSet);
++gDelayUpdateScrollInfo;
}
void RenderBlock::finishDelayUpdateScrollInfo()
{
--gDelayUpdateScrollInfo;
ASSERT(gDelayUpdateScrollInfo >= 0);
if (gDelayUpdateScrollInfo == 0) {
ASSERT(gDelayedUpdateScrollInfoSet);
OwnPtr<DelayedUpdateScrollInfoSet> infoSet(adoptPtr(gDelayedUpdateScrollInfoSet));
gDelayedUpdateScrollInfoSet = 0;
for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
RenderBlock* block = *it;
if (block->hasOverflowClip()) {
block->layer()->updateScrollInfoAfterLayout();
}
}
}
}
void RenderBlock::updateScrollInfoAfterLayout()
{
if (hasOverflowClip()) {
if (gDelayUpdateScrollInfo)
gDelayedUpdateScrollInfoSet->add(this);
else
layer()->updateScrollInfoAfterLayout();
}
}
void RenderBlock::layout()
{
OverflowEventDispatcher dispatcher(this);
updateFirstLetter();
layoutBlock(false);
if (hasControlClip() && m_overflow)
clearLayoutOverflow();
}
void RenderBlock::computeInitialRegionRangeForBlock()
{
if (inRenderFlowThread()) {
LayoutUnit oldHeight = logicalHeight();
LayoutUnit oldLogicalTop = logicalTop();
setLogicalHeight(MAX_LAYOUT_UNIT / 2);
computeLogicalHeight();
enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
setLogicalHeight(oldHeight);
setLogicalTop(oldLogicalTop);
}
}
void RenderBlock::computeRegionRangeForBlock()
{
if (inRenderFlowThread())
enclosingRenderFlowThread()->setRegionRangeForBox(this, offsetFromLogicalTopOfFirstPage());
}
bool RenderBlock::recomputeLogicalWidth()
{
LayoutUnit oldWidth = logicalWidth();
LayoutUnit oldColumnWidth = desiredColumnWidth();
computeLogicalWidth();
calcColumnWidth();
return oldWidth != logicalWidth() || oldColumnWidth != desiredColumnWidth();
}
void RenderBlock::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
{
ASSERT(needsLayout());
if (isInline() && !isInlineBlockOrInlineTable()) return;
if (!relayoutChildren && simplifiedLayout())
return;
LayoutRepainter repainter(*this, everHadLayout() && checkForRepaintDuringLayout());
if (recomputeLogicalWidth())
relayoutChildren = true;
m_overflow.clear();
clearFloats();
LayoutUnit previousHeight = logicalHeight();
setLogicalHeight(0);
bool hasSpecifiedPageLogicalHeight = false;
bool pageLogicalHeightChanged = false;
ColumnInfo* colInfo = columnInfo();
if (hasColumns()) {
if (!pageLogicalHeight) {
computeLogicalHeight();
LayoutUnit columnHeight = contentLogicalHeight();
if (columnHeight > 0) {
pageLogicalHeight = columnHeight;
hasSpecifiedPageLogicalHeight = true;
}
setLogicalHeight(0);
}
if (colInfo->columnHeight() != pageLogicalHeight && everHadLayout()) {
colInfo->setColumnHeight(pageLogicalHeight);
pageLogicalHeightChanged = true;
}
if (!hasSpecifiedPageLogicalHeight && !pageLogicalHeight)
colInfo->clearForcedBreaks();
colInfo->setPaginationUnit(paginationUnit());
}
RenderView* renderView = view();
RenderStyle* styleToUse = style();
LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, colInfo);
if (inRenderFlowThread()) {
if (logicalWidthChangedInRegions())
relayoutChildren = true;
}
computeInitialRegionRangeForBlock();
bool isCell = isTableCell();
if (!isCell) {
initMaxMarginValues();
setMarginBeforeQuirk(styleToUse->marginBefore().quirk());
setMarginAfterQuirk(styleToUse->marginAfter().quirk());
Node* n = node();
if (n && n->hasTagName(formTag) && static_cast<HTMLFormElement*>(n)->isMalformed()) {
setMaxMarginAfterValues(0, 0);
}
setPaginationStrut(0);
}
if (scrollsOverflow() && style()->appearance() != ListboxPart) {
if (styleToUse->overflowX() == OSCROLL)
layer()->setHasHorizontalScrollbar(true);
if (styleToUse->overflowY() == OSCROLL)
layer()->setHasVerticalScrollbar(true);
}
LayoutUnit repaintLogicalTop = 0;
LayoutUnit repaintLogicalBottom = 0;
LayoutUnit maxFloatLogicalBottom = 0;
if (!firstChild() && !isAnonymousBlock())
setChildrenInline(true);
if (childrenInline())
layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
else
layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom);
LayoutUnit toAdd = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
if (layoutColumns(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
return;
LayoutUnit oldHeight = logicalHeight();
LayoutUnit oldClientAfterEdge = clientLogicalBottom();
computeLogicalHeight();
LayoutUnit newHeight = logicalHeight();
if (oldHeight != newHeight) {
if (oldHeight > newHeight && maxFloatLogicalBottom > newHeight && !childrenInline()) {
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
RenderBlock* block = toRenderBlock(child);
if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
addOverhangingFloats(block, false);
}
}
}
}
if (previousHeight != newHeight)
relayoutChildren = true;
layoutPositionedObjects(relayoutChildren || isRoot());
computeRegionRangeForBlock();
computeOverflow(oldClientAfterEdge);
statePusher.pop();
if (renderView->layoutState()->m_pageLogicalHeight)
setPageLogicalOffset(renderView->layoutState()->pageLogicalOffset(this, logicalTop()));
updateLayerTransform();
updateScrollInfoAfterLayout();
bool didFullRepaint = repainter.repaintAfterLayout();
if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
if (hasOverflowClip()) {
repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
}
LayoutRect repaintRect;
if (isHorizontalWritingMode())
repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
else
repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
adjustRectForColumns(repaintRect);
repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
if (hasOverflowClip()) {
repaintRect.move(-scrolledContentOffset());
repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
}
if (!repaintRect.isEmpty()) {
repaintRectangle(repaintRect); if (hasReflection())
repaintRectangle(reflectedRect(repaintRect));
}
}
setNeedsLayout(false);
}
void RenderBlock::addOverflowFromChildren()
{
if (!hasColumns()) {
if (childrenInline())
addOverflowFromInlineChildren();
else
addOverflowFromBlockChildren();
} else {
ColumnInfo* colInfo = columnInfo();
if (columnCount(colInfo)) {
LayoutRect lastRect = columnRectAt(colInfo, columnCount(colInfo) - 1);
addLayoutOverflow(lastRect);
if (!hasOverflowClip())
addVisualOverflow(lastRect);
}
}
}
void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
{
addOverflowFromChildren();
if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
addOverflowFromFloats();
addOverflowFromPositionedObjects();
if (hasOverflowClip()) {
LayoutRect clientRect(clientBoxRect());
LayoutRect rectToApply;
if (isHorizontalWritingMode())
rectToApply = LayoutRect(clientRect.x(), clientRect.y(), 1, max<LayoutUnit>(0, oldClientAfterEdge - clientRect.y()));
else
rectToApply = LayoutRect(clientRect.x(), clientRect.y(), max<LayoutUnit>(0, oldClientAfterEdge - clientRect.x()), 1);
addLayoutOverflow(rectToApply);
}
addVisualEffectOverflow();
addVisualOverflowFromTheme();
if (isRenderFlowThread())
enclosingRenderFlowThread()->computeOverflowStateForRegions(oldClientAfterEdge);
}
void RenderBlock::addOverflowFromBlockChildren()
{
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (!child->isFloatingOrOutOfFlowPositioned())
addOverflowFromChild(child);
}
}
void RenderBlock::addOverflowFromFloats()
{
if (!m_floatingObjects)
return;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
if (r->isDescendant())
addOverflowFromChild(r->m_renderer, IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
}
return;
}
void RenderBlock::addOverflowFromPositionedObjects()
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
RenderBox* positionedObject;
TrackedRendererListHashSet::iterator end = positionedDescendants->end();
for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
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;
IntRect inflatedRect = pixelSnappedBorderBoxRect();
theme()->adjustRepaintRect(this, inflatedRect);
addVisualOverflow(inflatedRect);
}
bool RenderBlock::expandsToEncloseOverhangingFloats() const
{
return isInlineBlockOrInlineTable() || isFloatingOrOutOfFlowPositioned() || hasOverflowClip() || (parent() && parent()->isDeprecatedFlexibleBox())
|| hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
}
void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
{
bool isHorizontal = isHorizontalWritingMode();
bool hasStaticBlockPosition = child->style()->hasStaticBlockPosition(isHorizontal);
LayoutUnit logicalTop = logicalHeight();
setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
if (!marginInfo.canCollapseWithMarginBefore()) {
child->computeBlockDirectionMargins(this);
LayoutUnit marginBefore = marginBeforeForChild(child);
LayoutUnit collapsedBeforePos = marginInfo.positiveMargin();
LayoutUnit collapsedBeforeNeg = marginInfo.negativeMargin();
if (marginBefore > 0) {
if (marginBefore > collapsedBeforePos)
collapsedBeforePos = marginBefore;
} else {
if (-marginBefore > collapsedBeforeNeg)
collapsedBeforeNeg = -marginBefore;
}
logicalTop += (collapsedBeforePos - collapsedBeforeNeg) - marginBefore;
}
RenderLayer* childLayer = child->layer();
if (childLayer->staticBlockPosition() != logicalTop) {
childLayer->setStaticBlockPosition(logicalTop);
if (hasStaticBlockPosition)
child->setChildNeedsLayout(true, MarkOnlyThis);
}
}
void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
{
LayoutUnit marginOffset = marginInfo.canCollapseWithMarginBefore() ? ZERO_LAYOUT_UNIT : marginInfo.margin();
setLogicalHeight(logicalHeight() + marginOffset);
positionNewFloats();
setLogicalHeight(logicalHeight() - marginOffset);
}
bool RenderBlock::handleSpecialChild(RenderBox* child, const MarginInfo& marginInfo)
{
return handlePositionedChild(child, marginInfo)
|| handleFloatingChild(child, marginInfo);
}
bool RenderBlock::handlePositionedChild(RenderBox* child, const MarginInfo& marginInfo)
{
if (child->isOutOfFlowPositioned()) {
child->containingBlock()->insertPositionedObject(child);
adjustPositionedBlock(child, marginInfo);
return true;
}
return false;
}
bool RenderBlock::handleFloatingChild(RenderBox* child, const MarginInfo& marginInfo)
{
if (child->isFloating()) {
insertFloatingObject(child);
adjustFloatingBlock(marginInfo);
return true;
}
return false;
}
static void destroyRunIn(RenderBoxModelObject* runIn)
{
ASSERT(runIn->isRunIn());
ASSERT(!runIn->firstChild());
if (runIn->isRenderBlock())
toRenderBlock(runIn)->deleteLineBoxTree();
else if (runIn->isRenderInline())
toRenderInline(runIn)->deleteLineBoxTree();
else
ASSERT_NOT_REACHED();
runIn->destroy();
}
void RenderBlock::placeRunInIfNeeded(RenderObject* newChild, PlaceGeneratedRunInFlag flag)
{
if (newChild->isRunIn() && (flag == PlaceGeneratedRunIn || !newChild->isBeforeOrAfterContent()))
moveRunInUnderSiblingBlockIfNeeded(newChild);
else if (RenderObject* prevSibling = newChild->previousSibling()) {
if (prevSibling->isRunIn() && (flag == PlaceGeneratedRunIn || !newChild->isBeforeOrAfterContent()))
moveRunInUnderSiblingBlockIfNeeded(prevSibling);
}
}
RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
{
ASSERT(runIn->isRunIn());
if (runIn->style()->styleType() != BEFORE && runIn->style()->styleType() != AFTER) {
RenderObject* generatedContent;
if (runIn->getCachedPseudoStyle(BEFORE) && (generatedContent = runIn->beforePseudoElementRenderer()))
generatedContent->destroy();
if (runIn->getCachedPseudoStyle(AFTER) && (generatedContent = runIn->afterPseudoElementRenderer()))
generatedContent->destroy();
}
bool newRunInShouldBeBlock = !runIn->isRenderBlock();
Node* runInNode = runIn->node();
RenderBoxModelObject* newRunIn = 0;
if (newRunInShouldBeBlock)
newRunIn = new (renderArena()) RenderBlock(runInNode ? runInNode : document());
else
newRunIn = new (renderArena()) RenderInline(runInNode ? runInNode : document());
newRunIn->setStyle(runIn->style());
runIn->moveAllChildrenTo(newRunIn, true);
if (runInNode)
runInNode->setRenderer(newRunIn);
return newRunIn;
}
void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
{
ASSERT(runIn->isRunIn());
if (!runIn->childrenInline())
return;
if (!runIn->isRenderBlock())
return;
if (runIn->isElementContinuation() || runIn->virtualContinuation())
return;
if (!runIn->canBeReplacedWithInlineRunIn())
return;
RenderObject* curr = runIn->nextSibling();
if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
return;
if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
return;
if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
return;
RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
destroyRunIn(oldRunIn);
curr->addChild(newRunIn, curr->firstChild());
curr->setNeedsLayoutAndPrefWidthsRecalc();
}
bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
{
ASSERT(runIn->isRunIn());
if (!parent())
return false;
if (!runIn->isRenderInline())
return false;
return true;
}
void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
{
ASSERT(runIn->isRunIn());
if (!runInIsPlacedIntoSiblingBlock(runIn))
return;
if (runIn->isElementContinuation() || runIn->virtualContinuation())
return;
RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
destroyRunIn(oldRunIn);
parent()->addChild(newRunIn, this);
parent()->setNeedsLayoutAndPrefWidthsRecalc();
}
LayoutUnit RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
{
const MarginValues childMargins = marginValuesForChild(child);
LayoutUnit posTop = childMargins.positiveMarginBefore();
LayoutUnit negTop = childMargins.negativeMarginBefore();
if (child->isSelfCollapsingBlock()) {
posTop = max(posTop, childMargins.positiveMarginAfter());
negTop = max(negTop, childMargins.negativeMarginAfter());
}
bool topQuirk = child->isMarginBeforeQuirk() || style()->marginBeforeCollapse() == MDISCARD;
if (marginInfo.canCollapseWithMarginBefore()) {
if (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !topQuirk)
setMaxMarginBeforeValues(max(posTop, maxPositiveMarginBefore()), max(negTop, maxNegativeMarginBefore()));
if (!marginInfo.determinedMarginBeforeQuirk() && !topQuirk && (posTop - negTop)) {
setMarginBeforeQuirk(false);
marginInfo.setDeterminedMarginBeforeQuirk(true);
}
if (!marginInfo.determinedMarginBeforeQuirk() && topQuirk && !marginBefore())
setMarginBeforeQuirk(true);
}
if (marginInfo.quirkContainer() && marginInfo.atBeforeSideOfBlock() && (posTop - negTop))
marginInfo.setMarginBeforeQuirk(topQuirk);
LayoutUnit beforeCollapseLogicalTop = logicalHeight();
LayoutUnit logicalTop = beforeCollapseLogicalTop;
if (child->isSelfCollapsingBlock()) {
LayoutUnit collapsedBeforePos = max(marginInfo.positiveMargin(), childMargins.positiveMarginBefore());
LayoutUnit collapsedBeforeNeg = max(marginInfo.negativeMargin(), childMargins.negativeMarginBefore());
marginInfo.setMargin(collapsedBeforePos, collapsedBeforeNeg);
marginInfo.setPositiveMarginIfLarger(childMargins.positiveMarginAfter());
marginInfo.setNegativeMarginIfLarger(childMargins.negativeMarginAfter());
if (!marginInfo.canCollapseWithMarginBefore())
logicalTop = logicalHeight() + collapsedBeforePos - collapsedBeforeNeg;
}
else {
if (child->style()->marginBeforeCollapse() == MSEPARATE) {
setLogicalHeight(logicalHeight() + marginInfo.margin() + marginBeforeForChild(child));
logicalTop = logicalHeight();
}
else if (!marginInfo.atBeforeSideOfBlock() ||
(!marginInfo.canCollapseMarginBeforeWithChildren()
&& (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginBeforeQuirk()))) {
setLogicalHeight(logicalHeight() + max(marginInfo.positiveMargin(), posTop) - max(marginInfo.negativeMargin(), negTop));
logicalTop = logicalHeight();
}
marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
if (marginInfo.margin())
marginInfo.setMarginAfterQuirk(child->isMarginAfterQuirk() || style()->marginAfterCollapse() == MDISCARD);
}
LayoutState* layoutState = view()->layoutState();
if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTop > beforeCollapseLogicalTop
&& hasNextPage(beforeCollapseLogicalTop)) {
LayoutUnit oldLogicalTop = logicalTop;
logicalTop = min(logicalTop, nextPageLogicalTop(beforeCollapseLogicalTop));
setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
}
RenderObject* prev = child->previousSibling();
if (prev && prev->isBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
RenderBlock* block = toRenderBlock(prev);
if (block->containsFloats() && block->lowestFloatLogicalBottom() > logicalTop)
addOverhangingFloats(block, false);
}
return logicalTop;
}
LayoutUnit RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, LayoutUnit oldTopPosMargin, LayoutUnit oldTopNegMargin, LayoutUnit yPos)
{
LayoutUnit heightIncrease = getClearDelta(child, yPos);
if (!heightIncrease)
return yPos;
if (child->isSelfCollapsingBlock()) {
bool atBottomOfBlock = true;
for (RenderBox* curr = child->nextSiblingBox(); curr && atBottomOfBlock; curr = curr->nextSiblingBox()) {
if (!curr->isFloatingOrOutOfFlowPositioned())
atBottomOfBlock = false;
}
MarginValues childMargins = marginValuesForChild(child);
if (atBottomOfBlock) {
marginInfo.setPositiveMargin(childMargins.positiveMarginAfter());
marginInfo.setNegativeMargin(childMargins.negativeMarginAfter());
} else {
marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
}
setLogicalHeight(child->logicalTop() - max<LayoutUnit>(0, marginInfo.margin()));
} else
setLogicalHeight(logicalHeight() + heightIncrease);
if (marginInfo.canCollapseWithMarginBefore()) {
setMaxMarginBeforeValues(oldTopPosMargin, oldTopNegMargin);
marginInfo.setAtBeforeSideOfBlock(false);
}
return yPos + heightIncrease;
}
void RenderBlock::marginBeforeEstimateForChild(RenderBox* child, LayoutUnit& positiveMarginBefore, LayoutUnit& negativeMarginBefore) const
{
if (document()->inQuirksMode() && child->isMarginBeforeQuirk() && (isTableCell() || isBody()))
return;
LayoutUnit beforeChildMargin = marginBeforeForChild(child);
positiveMarginBefore = max(positiveMarginBefore, beforeChildMargin);
negativeMarginBefore = max(negativeMarginBefore, -beforeChildMargin);
if (!child->isRenderBlock())
return;
RenderBlock* childBlock = toRenderBlock(child);
if (childBlock->childrenInline() || childBlock->isWritingModeRoot())
return;
MarginInfo childMarginInfo(childBlock, childBlock->borderBefore() + childBlock->paddingBefore(), childBlock->borderAfter() + childBlock->paddingAfter());
if (!childMarginInfo.canCollapseMarginBeforeWithChildren())
return;
RenderBox* grandchildBox = childBlock->firstChildBox();
for ( ; grandchildBox; grandchildBox = grandchildBox->nextSiblingBox()) {
if (!grandchildBox->isFloatingOrOutOfFlowPositioned())
break;
}
if (!grandchildBox || grandchildBox->style()->clear() != CNONE)
return;
if (grandchildBox->needsLayout()) {
grandchildBox->computeBlockDirectionMargins(this);
grandchildBox->setMarginBeforeQuirk(grandchildBox->style()->marginBefore().quirk());
grandchildBox->setMarginAfterQuirk(grandchildBox->style()->marginAfter().quirk());
}
childBlock->marginBeforeEstimateForChild(grandchildBox, positiveMarginBefore, negativeMarginBefore);
}
LayoutUnit RenderBlock::estimateLogicalTopPosition(RenderBox* child, const MarginInfo& marginInfo, LayoutUnit& estimateWithoutPagination)
{
LayoutUnit logicalTopEstimate = logicalHeight();
if (!marginInfo.canCollapseWithMarginBefore()) {
LayoutUnit positiveMarginBefore = ZERO_LAYOUT_UNIT;
LayoutUnit negativeMarginBefore = ZERO_LAYOUT_UNIT;
if (child->selfNeedsLayout()) {
marginBeforeEstimateForChild(child, positiveMarginBefore, negativeMarginBefore);
} else {
MarginValues marginValues = marginValuesForChild(child);
positiveMarginBefore = max(positiveMarginBefore, marginValues.positiveMarginBefore());
negativeMarginBefore = max(negativeMarginBefore, marginValues.negativeMarginBefore());
}
logicalTopEstimate += max(marginInfo.positiveMargin(), positiveMarginBefore) - max(marginInfo.negativeMargin(), negativeMarginBefore);
}
LayoutState* layoutState = view()->layoutState();
if (layoutState->isPaginated() && layoutState->pageLogicalHeight() && logicalTopEstimate > logicalHeight()
&& hasNextPage(logicalHeight()))
logicalTopEstimate = min(logicalTopEstimate, nextPageLogicalTop(logicalHeight()));
logicalTopEstimate += getClearDelta(child, logicalTopEstimate);
estimateWithoutPagination = logicalTopEstimate;
if (layoutState->isPaginated()) {
logicalTopEstimate = applyBeforeBreak(child, logicalTopEstimate);
logicalTopEstimate = adjustForUnsplittableChild(child, logicalTopEstimate);
if (!child->selfNeedsLayout() && child->isRenderBlock())
logicalTopEstimate += toRenderBlock(child)->paginationStrut();
}
return logicalTopEstimate;
}
LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart,
RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage)
{
LayoutUnit startPosition = startOffsetForContent(region, offsetFromLogicalTopOfFirstPage);
LayoutUnit oldPosition = startPosition + childMarginStart;
LayoutUnit newPosition = oldPosition;
LayoutUnit blockOffset = logicalTopForChild(child);
if (region)
blockOffset = max(blockOffset, blockOffset + (region->offsetFromLogicalTopOfFirstPage() - offsetFromLogicalTopOfFirstPage));
LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, offsetFromLogicalTopOfFirstPage);
if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
if (childMarginStart < 0)
startOff += childMarginStart;
newPosition = max(newPosition, startOff); } else if (startOff != startPosition)
newPosition = startOff + childMarginStart;
return newPosition - oldPosition;
}
void RenderBlock::determineLogicalLeftPositionForChild(RenderBox* child)
{
LayoutUnit startPosition = borderStart() + paddingStart();
if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
startPosition -= verticalScrollbarWidth();
LayoutUnit totalAvailableLogicalWidth = borderAndPaddingLogicalWidth() + availableLogicalWidth();
LayoutUnit childMarginStart = marginStartForChild(child);
LayoutUnit newPosition = startPosition + childMarginStart;
if (child->avoidsFloats() && containsFloats() && !inRenderFlowThread())
newPosition += computeStartPositionDeltaForChildAvoidingFloats(child, marginStartForChild(child));
setLogicalLeftForChild(child, style()->isLeftToRightDirection() ? newPosition : totalAvailableLogicalWidth - newPosition - logicalWidthForChild(child), ApplyLayoutDelta);
}
void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
{
if (marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()) {
setMaxMarginAfterValues(max(maxPositiveMarginAfter(), marginInfo.positiveMargin()), max(maxNegativeMarginAfter(), marginInfo.negativeMargin()));
if (!marginInfo.marginAfterQuirk())
setMarginAfterQuirk(false);
if (marginInfo.marginAfterQuirk() && marginAfter() == 0)
setMarginAfterQuirk(true);
}
}
void RenderBlock::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit afterSide, MarginInfo& marginInfo)
{
marginInfo.setAtAfterSideOfBlock(true);
if (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
&& (!document()->inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.marginAfterQuirk()))
setLogicalHeight(logicalHeight() + marginInfo.margin());
setLogicalHeight(logicalHeight() + afterSide);
setLogicalHeight(max(logicalHeight(), beforeSide + afterSide));
setCollapsedBottomMargin(marginInfo);
}
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::layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom)
{
if (gPercentHeightDescendantsMap) {
if (TrackedRendererListHashSet* descendants = gPercentHeightDescendantsMap->get(this)) {
TrackedRendererListHashSet::iterator end = descendants->end();
for (TrackedRendererListHashSet::iterator it = descendants->begin(); it != end; ++it) {
RenderBox* box = *it;
while (box != this) {
if (box->normalChildNeedsLayout())
break;
box->setChildNeedsLayout(true, MarkOnlyThis);
box = box->containingBlock();
ASSERT(box);
if (!box)
break;
}
}
}
}
LayoutUnit beforeEdge = borderBefore() + paddingBefore();
LayoutUnit afterEdge = borderAfter() + paddingAfter() + scrollbarLogicalHeight();
setLogicalHeight(beforeEdge);
if (view()->layoutState()->lineGrid() == this)
layoutLineGridBox();
MarginInfo marginInfo(this, beforeEdge, afterEdge);
RenderObject* childToExclude = layoutSpecialExcludedChild(relayoutChildren);
LayoutUnit previousFloatLogicalBottom = 0;
maxFloatLogicalBottom = 0;
RenderBox* next = firstChildBox();
while (next) {
RenderBox* child = next;
next = child->nextSiblingBox();
if (childToExclude == child)
continue;
if (relayoutChildren || (child->hasRelativeLogicalHeight() && !isRenderView()))
child->setChildNeedsLayout(true, MarkOnlyThis);
if (relayoutChildren && child->needsPreferredWidthsRecalculation())
child->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
if (handleSpecialChild(child, marginInfo))
continue;
layoutBlockChild(child, marginInfo, previousFloatLogicalBottom, maxFloatLogicalBottom);
}
handleAfterSideOfBlock(beforeEdge, afterEdge, marginInfo);
}
void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, LayoutUnit& previousFloatLogicalBottom, LayoutUnit& maxFloatLogicalBottom)
{
LayoutUnit oldPosMarginBefore = maxPositiveMarginBefore();
LayoutUnit oldNegMarginBefore = maxNegativeMarginBefore();
child->computeBlockDirectionMargins(this);
RenderStyle* childStyle = child->style();
if (childStyle->marginBeforeCollapse() == MSEPARATE) {
marginInfo.setAtBeforeSideOfBlock(false);
marginInfo.clearMargin();
}
LayoutUnit estimateWithoutPagination;
LayoutUnit logicalTopEstimate = estimateLogicalTopPosition(child, marginInfo, estimateWithoutPagination);
LayoutRect oldRect(child->x(), child->y() , child->width(), child->height());
LayoutUnit oldLogicalTop = logicalTopForChild(child);
#if !ASSERT_DISABLED
LayoutSize oldLayoutDelta = view()->layoutDelta();
#endif
setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
bool markDescendantsWithFloats = false;
if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats())
markDescendantsWithFloats = true;
else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
LayoutUnit fb = max(previousFloatLogicalBottom, lowestFloatLogicalBottom());
if (fb > logicalTopEstimate)
markDescendantsWithFloats = true;
}
if (childRenderBlock) {
if (markDescendantsWithFloats)
childRenderBlock->markAllDescendantsWithFloatsForLayout();
if (!child->isWritingModeRoot())
previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
}
if (!child->needsLayout())
child->markForPaginationRelayoutIfNeeded();
bool childHadLayout = child->everHadLayout();
bool childNeededLayout = child->needsLayout();
if (childNeededLayout)
child->layout();
bool atBeforeSideOfBlock = marginInfo.atBeforeSideOfBlock();
LayoutUnit logicalTopBeforeClear = collapseMargins(child, marginInfo);
LayoutUnit logicalTopAfterClear = clearFloatsIfNeeded(child, marginInfo, oldPosMarginBefore, oldNegMarginBefore, logicalTopBeforeClear);
bool paginated = view()->layoutState()->isPaginated();
if (paginated)
logicalTopAfterClear = adjustBlockChildForPagination(logicalTopAfterClear, estimateWithoutPagination, child,
atBeforeSideOfBlock && logicalTopBeforeClear == logicalTopAfterClear);
setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
if (logicalTopAfterClear != logicalTopEstimate || child->needsLayout()) {
if (child->shrinkToAvoidFloats()) {
child->setChildNeedsLayout(true, MarkOnlyThis);
}
if (childRenderBlock) {
if (!child->avoidsFloats() && childRenderBlock->containsFloats())
childRenderBlock->markAllDescendantsWithFloatsForLayout();
if (!child->needsLayout())
child->markForPaginationRelayoutIfNeeded();
}
child->layoutIfNeeded();
}
if (marginInfo.atBeforeSideOfBlock() && !child->isSelfCollapsingBlock())
marginInfo.setAtBeforeSideOfBlock(false);
determineLogicalLeftPositionForChild(child);
setLogicalHeight(logicalHeight() + logicalHeightForChild(child));
if (childStyle->marginAfterCollapse() == MSEPARATE) {
setLogicalHeight(logicalHeight() + marginAfterForChild(child));
marginInfo.clearMargin();
}
if (childRenderBlock && childRenderBlock->containsFloats())
maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
LayoutSize childOffset(child->x() - oldRect.x(), child->y() - oldRect.y());
if (childOffset.width() || childOffset.height()) {
view()->addLayoutDelta(childOffset);
if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
child->repaintDuringLayoutIfMoved(oldRect);
}
if (!childHadLayout && child->checkForRepaintDuringLayout()) {
child->repaint();
child->repaintOverhangingFloats(true);
}
if (paginated) {
LayoutUnit newHeight = applyAfterBreak(child, logicalHeight(), marginInfo);
if (newHeight != height())
setLogicalHeight(newHeight);
}
ASSERT(oldLayoutDelta == view()->layoutDelta());
}
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())) {
o->layoutIfNeeded();
if (toRenderBox(o)->inlineBoxWrapper()) {
RootInlineBox* box = toRenderBox(o)->inlineBoxWrapper()->root();
lineBoxes.add(box);
}
} else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline()))
o->setNeedsLayout(false);
}
GlyphOverflowAndFallbackFontsMap textBoxDataMap;
for (ListHashSet<RootInlineBox*>::const_iterator it = lineBoxes.begin(); it != lineBoxes.end(); ++it) {
RootInlineBox* box = *it;
box->computeOverflow(box->lineTop(), box->lineBottom(), textBoxDataMap);
}
} else {
for (RenderBox* 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(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
if (needsPositionedMovementLayout() && !tryLayoutDoingPositionedMovementOnly())
return false;
if (needsSimplifiedNormalFlowLayout())
simplifiedNormalFlowLayout();
if (posChildNeedsLayout())
layoutPositionedObjects(false);
m_overflow.clear();
computeOverflow(clientLogicalBottom(), true);
statePusher.pop();
updateLayerTransform();
updateScrollInfoAfterLayout();
setNeedsLayout(false);
return true;
}
void RenderBlock::layoutPositionedObjects(bool relayoutChildren)
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
if (hasColumns())
view()->layoutState()->clearPaginationInformation();
RenderBox* r;
TrackedRendererListHashSet::iterator end = positionedDescendants->end();
for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
r = *it;
if (relayoutChildren || (r->style()->hasStaticBlockPosition(isHorizontalWritingMode()) && r->parent() != this))
r->setChildNeedsLayout(true, MarkOnlyThis);
if (relayoutChildren && r->needsPreferredWidthsRecalculation())
r->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
if (!r->needsLayout())
r->markForPaginationRelayoutIfNeeded();
if (r->needsPositionedMovementLayoutOnly() && r->tryLayoutDoingPositionedMovementOnly())
r->setNeedsLayout(false);
LayoutUnit oldLogicalTop = 0;
bool needsBlockDirectionLocationSetBeforeLayout = r->needsLayout() && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
if (needsBlockDirectionLocationSetBeforeLayout) {
if (isHorizontalWritingMode() == r->isHorizontalWritingMode())
r->computeLogicalHeight();
else
r->computeLogicalWidth();
oldLogicalTop = logicalTopForChild(r);
}
r->layoutIfNeeded();
if (needsBlockDirectionLocationSetBeforeLayout && logicalTopForChild(r) != oldLogicalTop) {
r->setChildNeedsLayout(true, MarkOnlyThis);
r->layoutIfNeeded();
}
}
if (hasColumns())
view()->layoutState()->m_columnInfo = columnInfo(); }
void RenderBlock::markPositionedObjectsForLayout()
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (positionedDescendants) {
RenderBox* r;
TrackedRendererListHashSet::iterator end = positionedDescendants->end();
for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
r = *it;
r->setChildNeedsLayout(true);
}
}
}
void RenderBlock::markForPaginationRelayoutIfNeeded()
{
ASSERT(!needsLayout());
if (needsLayout())
return;
if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
setChildNeedsLayout(true, MarkOnlyThis);
}
void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
{
if (!hasOverhangingFloats())
return;
LayoutStateDisabler layoutStateDisabler(view());
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
if (logicalBottomForFloat(r) > logicalHeight() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->shouldPaint()) && !r->m_renderer->hasSelfPaintingLayer()) {
r->m_renderer->repaint();
r->m_renderer->repaintOverhangingFloats();
}
}
}
void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
LayoutPoint adjustedPaintOffset = paintOffset + location();
PaintPhase phase = paintInfo.phase;
if (!isRoot()) {
LayoutRect overflowBox = visualOverflowRect();
flipForWritingMode(overflowBox);
overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
overflowBox.moveBy(adjustedPaintOffset);
if (!overflowBox.intersects(paintInfo.rect)
&& (!hasLayer() || !layer()->isComposited())
)
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))
layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
}
void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (paintInfo.context->paintingDisabled())
return;
const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
bool ruleTransparent = style()->columnRuleIsTransparent();
EBorderStyle ruleStyle = style()->columnRuleStyle();
LayoutUnit ruleThickness = style()->columnRuleWidth();
LayoutUnit colGap = columnGap();
bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent && ruleThickness <= colGap;
if (!renderRule)
return;
ColumnInfo* colInfo = columnInfo();
unsigned colCount = columnCount(colInfo);
bool antialias = shouldAntialiasLines(paintInfo.context);
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
bool leftToRight = style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed();
LayoutUnit currLogicalLeftOffset = leftToRight ? ZERO_LAYOUT_UNIT : contentLogicalWidth();
LayoutUnit ruleAdd = logicalLeftOffsetForContent();
LayoutUnit ruleLogicalLeft = leftToRight ? ZERO_LAYOUT_UNIT : contentLogicalWidth();
LayoutUnit inlineDirectionSize = colInfo->desiredColumnWidth();
BoxSide boxSide = isHorizontalWritingMode()
? leftToRight ? BSLeft : BSRight
: leftToRight ? BSTop : BSBottom;
for (unsigned i = 0; i < colCount; i++) {
if (leftToRight) {
ruleLogicalLeft += inlineDirectionSize + colGap / 2;
currLogicalLeftOffset += inlineDirectionSize + colGap;
} else {
ruleLogicalLeft -= (inlineDirectionSize + colGap / 2);
currLogicalLeftOffset -= (inlineDirectionSize + colGap);
}
if (i < colCount - 1) {
LayoutUnit ruleLeft = isHorizontalWritingMode() ? paintOffset.x() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd : paintOffset.x() + borderLeft() + paddingLeft();
LayoutUnit ruleRight = isHorizontalWritingMode() ? ruleLeft + ruleThickness : ruleLeft + contentWidth();
LayoutUnit ruleTop = isHorizontalWritingMode() ? paintOffset.y() + borderTop() + paddingTop() : paintOffset.y() + ruleLogicalLeft - ruleThickness / 2 + ruleAdd;
LayoutUnit ruleBottom = isHorizontalWritingMode() ? ruleTop + contentHeight() : ruleTop + ruleThickness;
IntRect pixelSnappedRuleRect = pixelSnappedIntRectFromEdges(ruleLeft, ruleTop, ruleRight, ruleBottom);
drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
}
ruleLogicalLeft = currLogicalLeftOffset;
}
} else {
bool topToBottom = !style()->isFlippedBlocksWritingMode() ^ colInfo->progressionIsReversed();
LayoutUnit ruleLeft = isHorizontalWritingMode()
? borderLeft() + paddingLeft()
: colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter());
LayoutUnit ruleWidth = isHorizontalWritingMode() ? contentWidth() : ruleThickness;
LayoutUnit ruleTop = isHorizontalWritingMode()
? colGap / 2 - colGap - ruleThickness / 2 + (!colInfo->progressionIsReversed() ? borderBefore() + paddingBefore() : borderAfter() + paddingAfter())
: borderStart() + paddingStart();
LayoutUnit ruleHeight = isHorizontalWritingMode() ? ruleThickness : contentHeight();
LayoutRect ruleRect(ruleLeft, ruleTop, ruleWidth, ruleHeight);
if (!topToBottom) {
if (isHorizontalWritingMode())
ruleRect.setY(height() - ruleRect.maxY());
else
ruleRect.setX(width() - ruleRect.maxX());
}
ruleRect.moveBy(paintOffset);
BoxSide boxSide = isHorizontalWritingMode()
? topToBottom ? BSTop : BSBottom
: topToBottom ? BSLeft : BSRight;
LayoutSize step(0, topToBottom ? colInfo->columnHeight() + colGap : -(colInfo->columnHeight() + colGap));
if (!isHorizontalWritingMode())
step = step.transposedSize();
for (unsigned i = 1; i < colCount; i++) {
ruleRect.move(step);
IntRect pixelSnappedRuleRect = pixelSnappedIntRect(ruleRect);
drawLineForBoxSide(paintInfo.context, pixelSnappedRuleRect.x(), pixelSnappedRuleRect.y(), pixelSnappedRuleRect.maxX(), pixelSnappedRuleRect.maxY(), boxSide, ruleColor, ruleStyle, 0, 0, antialias);
}
}
}
void RenderBlock::paintColumnContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool paintingFloats)
{
GraphicsContext* context = paintInfo.context;
ColumnInfo* colInfo = columnInfo();
unsigned colCount = columnCount(colInfo);
if (!colCount)
return;
LayoutUnit currLogicalTopOffset = 0;
for (unsigned i = 0; i < colCount; i++) {
LayoutRect colRect = columnRectAt(colInfo, i);
flipForWritingMode(colRect);
LayoutUnit logicalLeftOffset = (isHorizontalWritingMode() ? colRect.x() : colRect.y()) - logicalLeftOffsetForContent();
LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(logicalLeftOffset, currLogicalTopOffset) : LayoutSize(currLogicalTopOffset, logicalLeftOffset);
if (colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
if (isHorizontalWritingMode())
offset.expand(0, colRect.y() - borderTop() - paddingTop());
else
offset.expand(colRect.x() - borderLeft() - paddingLeft(), 0);
}
colRect.moveBy(paintOffset);
PaintInfo info(paintInfo);
info.rect.intersect(pixelSnappedIntRect(colRect));
if (!info.rect.isEmpty()) {
GraphicsContextStateSaver stateSaver(*context);
context->clip(colRect);
LayoutPoint adjustedPaintOffset = paintOffset + offset;
if (paintingFloats)
paintFloats(info, adjustedPaintOffset, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
else
paintContents(info, adjustedPaintOffset);
}
LayoutUnit blockDelta = (isHorizontalWritingMode() ? colRect.height() : colRect.width());
if (style()->isFlippedBlocksWritingMode())
currLogicalTopOffset += blockDelta;
else
currLogicalTopOffset -= blockDelta;
}
}
void RenderBlock::paintContents(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
return;
if (childrenInline())
m_lineBoxes.paint(this, paintInfo, paintOffset);
else
paintChildren(paintInfo, paintOffset);
}
void RenderBlock::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
PaintInfo info(paintInfo);
info.phase = newPhase;
info.updatePaintingRootForChildren(this);
RenderView* renderView = view();
bool usePrintRect = !renderView->printRect().isEmpty();
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
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;
}
if (!child->isFloating() && child->isReplaced() && usePrintRect && child->height() <= renderView->printRect().height()) {
if (absoluteChildY + child->height() > renderView->printRect().maxY()) {
if (absoluteChildY < renderView->truncatedAt())
renderView->setBestTruncatedAt(absoluteChildY, child);
if (absoluteChildY >= renderView->truncatedAt())
break;
}
}
LayoutPoint childPoint = flipForWritingModeForChild(child, paintOffset);
if (!child->hasSelfPaintingLayer() && !child->isFloating())
child->paint(info, 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() + max<LayoutUnit>(0, child->collapsedMarginAfter()), this, true);
return;
}
}
}
void RenderBlock::paintCaret(PaintInfo& paintInfo, const LayoutPoint& paintOffset, CaretType type)
{
bool caretBrowsing = frame()->settings() && frame()->settings()->caretBrowsingEnabled();
RenderObject* caretPainter;
bool isContentEditable;
if (type == CursorCaret) {
caretPainter = frame()->selection()->caretRenderer();
isContentEditable = frame()->selection()->isContentEditable();
} 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())
paintBoxDecorations(paintInfo, paintOffset);
if (hasColumns())
paintColumnRules(paintInfo, paintOffset);
}
if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
paintMask(paintInfo, paintOffset);
return;
}
if (paintPhase == PaintPhaseBlockBackground)
return;
LayoutPoint scrolledOffset = paintOffset;
if (hasOverflowClip())
scrolledOffset.move(-scrolledContentOffset());
if (paintPhase != PaintPhaseSelfOutline) {
if (hasColumns())
paintColumnContents(paintInfo, scrolledOffset);
else
paintContents(paintInfo, scrolledOffset);
}
bool isPrinting = document()->printing();
if (!isPrinting && !hasColumns())
paintSelection(paintInfo, scrolledOffset);
if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
if (hasColumns())
paintColumnContents(paintInfo, scrolledOffset, true);
else
paintFloats(paintInfo, scrolledOffset, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
}
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
paintOutline(paintInfo.context, LayoutRect(paintOffset, size()));
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
RenderInline* inlineCont = inlineElementContinuation();
if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE && !hasLayer()) {
RenderInline* inlineRenderer = toRenderInline(inlineCont->node()->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)
cb->addContinuationWithOutline(inlineRenderer);
else if (!inlineRenderer->firstLineBox())
inlineRenderer->paintOutline(paintInfo.context, paintOffset - locationOffset() + inlineRenderer->containingBlock()->location());
}
paintContinuationOutlines(paintInfo, paintOffset);
}
if (paintPhase == PaintPhaseForeground) {
paintCaret(paintInfo, paintOffset, CursorCaret);
paintCaret(paintInfo, paintOffset, DragCaret);
}
}
LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
{
if (!style()->isFlippedBlocksWritingMode())
return point;
if (isHorizontalWritingMode())
return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
return LayoutPoint(point.x() + width() - child->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
}
void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
{
if (!m_floatingObjects)
return;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
if (r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()) {
PaintInfo currentPaintInfo(paintInfo);
currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->m_renderer->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->m_renderer->y()));
r->m_renderer->paint(currentPaintInfo, childPoint);
if (!preservePhase) {
currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
r->m_renderer->paint(currentPaintInfo, childPoint);
currentPaintInfo.phase = PaintPhaseFloat;
r->m_renderer->paint(currentPaintInfo, childPoint);
currentPaintInfo.phase = PaintPhaseForeground;
r->m_renderer->paint(currentPaintInfo, childPoint);
currentPaintInfo.phase = PaintPhaseOutline;
r->m_renderer->paint(currentPaintInfo, childPoint);
}
}
}
}
void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (!paintInfo.shouldPaintWithinRoot(this) || !firstLineBox())
return;
if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
LayoutUnit yPos = paintOffset.y() + firstLineBox()->y();
LayoutUnit h = lastLineBox()->y() + lastLineBox()->logicalHeight() - firstLineBox()->y();
if (yPos >= paintInfo.rect.maxY() || yPos + h <= paintInfo.rect.y())
return;
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
yPos = paintOffset.y() + curr->y();
h = curr->logicalHeight();
if (curr->ellipsisBox() && yPos < paintInfo.rect.maxY() && yPos + h > paintInfo.rect.y())
curr->paintEllipsisBox(paintInfo, paintOffset, curr->lineTop(), curr->lineBottom());
}
}
}
RenderInline* RenderBlock::inlineElementContinuation() const
{
RenderBoxModelObject* continuation = this->continuation();
return continuation && continuation->isInline() ? 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()
{
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, 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;
ListHashSet<RenderInline*>* continuations = table->get(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.context, accumulatedPaintOffset);
}
delete continuations;
table->remove(this);
}
bool RenderBlock::shouldPaintSelectionGaps() const
{
return selectionState() != SelectionNone && style()->visibility() == VISIBLE && isSelectionRoot();
}
bool RenderBlock::isSelectionRoot() const
{
if (!node())
return false;
if (isTable())
return false;
if (isBody() || isRoot() || hasOverflowClip()
|| isPositioned() || isFloating()
|| isTableCell() || isInlineBlockOrInlineTable()
|| hasTransform() || hasReflection() || hasMask() || isWritingModeRoot())
return true;
if (view() && view()->selectionStart()) {
Node* startElement = view()->selectionStart()->node();
if (startElement && startElement->rootEditableElement() == node())
return true;
}
return false;
}
GapRects RenderBlock::selectionGapRectsForRepaint(RenderBoxModelObject* repaintContainer)
{
ASSERT(!needsLayout());
if (!shouldPaintSelectionGaps())
return GapRects();
TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
mapLocalToContainer(repaintContainer, false, false, transformState);
LayoutPoint offsetFromRepaintContainer = roundedLayoutPoint(transformState.mappedPoint());
if (hasOverflowClip())
offsetFromRepaintContainer -= scrolledContentOffset();
LayoutUnit lastTop = 0;
LayoutUnit lastLeft = logicalLeftSelectionOffset(this, lastTop);
LayoutUnit lastRight = logicalRightSelectionOffset(this, lastTop);
return selectionGaps(this, offsetFromRepaintContainer, IntSize(), lastTop, lastLeft, lastRight);
}
void RenderBlock::paintSelection(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(paintOffset);
return;
}
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()));
}
}
static int blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
{
return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
}
static int 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 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()); if (m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
r->m_renderer->width(), r->m_renderer->height());
rootBlock->flipForWritingMode(floatBox);
floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
}
}
}
GapRects result;
if (!isBlockFlow()) return result;
if (hasColumns() || hasTransform() || style()->columnSpan()) {
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
return result;
}
if (childrenInline())
result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
else
result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
logicalHeight(), paintInfo));
return result;
}
GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
{
GapRects result;
bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
if (!firstLineBox()) {
if (containsStart) {
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
}
return result;
}
RootInlineBox* lastSelectedLine = 0;
RootInlineBox* curr;
for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
if (!containsStart && !lastSelectedLine &&
selectionState() != SelectionStart && selectionState() != SelectionBoth)
result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
selTop, paintInfo));
LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
|| (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
lastSelectedLine = curr;
}
if (containsStart && !lastSelectedLine)
lastSelectedLine = lastRootBox();
if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
}
return result;
}
GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
{
GapRects result;
RenderBox* curr;
for (curr = firstChildBox(); curr && curr->selectionState() == SelectionNone; curr = curr->nextSiblingBox()) { }
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(), 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(), paintInfo));
if (rightGap)
result.uniteRight(logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, this, curr->logicalRight(), curr->logicalTop(), curr->logicalHeight(), paintInfo));
lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
} else if (childState != SelectionNone)
result.unite(toRenderBlock(curr)->selectionGaps(rootBlock, rootBlockPhysicalPosition, LayoutSize(offsetFromRootBlock.width() + curr->x(), offsetFromRootBlock.height() + curr->y()),
lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo));
}
return result;
}
LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
{
LayoutUnit logicalTop = lastLogicalTop;
LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
if (logicalHeight <= static_cast<LayoutUnit>(0))
return LayoutRect();
LayoutUnit logicalLeft = max(lastLogicalLeft, logicalLeftSelectionOffset(rootBlock, logicalBottom));
LayoutUnit logicalRight = min(lastLogicalRight, logicalRightSelectionOffset(rootBlock, logicalBottom));
LayoutUnit logicalWidth = logicalRight - logicalLeft;
if (logicalWidth <= static_cast<LayoutUnit>(0))
return LayoutRect();
LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(logicalLeft, logicalTop, logicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(gapRect, 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 PaintInfo* paintInfo)
{
LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalLeft, min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
return LayoutRect();
LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(gapRect, 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 PaintInfo* paintInfo)
{
LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + logicalRight, max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= static_cast<LayoutUnit>(0))
return LayoutRect();
LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, LayoutRect(rootBlockLogicalLeft, rootBlockLogicalTop, rootBlockLogicalWidth, logicalHeight));
if (paintInfo)
paintInfo->context->fillRect(gapRect, 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)
{
LayoutUnit logicalLeft = logicalLeftOffsetForLine(position, false);
if (logicalLeft == logicalLeftOffsetForContent()) {
if (rootBlock != this)
return containingBlock()->logicalLeftSelectionOffset(rootBlock, position + logicalTop());
return logicalLeft;
} else {
RenderBlock* cb = this;
while (cb != rootBlock) {
logicalLeft += cb->logicalLeft();
cb = cb->containingBlock();
}
}
return logicalLeft;
}
LayoutUnit RenderBlock::logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position)
{
LayoutUnit logicalRight = logicalRightOffsetForLine(position, false);
if (logicalRight == logicalRightOffsetForContent()) {
if (rootBlock != this)
return containingBlock()->logicalRightSelectionOffset(rootBlock, position + logicalTop());
return logicalRight;
} else {
RenderBlock* cb = this;
while (cb != rootBlock) {
logicalRight += cb->logicalLeft();
cb = cb->containingBlock();
}
}
return logicalRight;
}
RenderBlock* RenderBlock::blockBeforeWithinSelectionRoot(LayoutSize& offset) const
{
if (isSelectionRoot())
return 0;
const RenderObject* 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, 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, containerSet);
}
ASSERT(!containerSet->contains(this));
containerSet->add(this);
}
void RenderBlock::removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*& descendantsMap, TrackedContainerMap*& containerMap)
{
if (!descendantsMap)
return;
HashSet<RenderBlock*>* containerSet = containerMap->take(descendant);
if (!containerSet)
return;
HashSet<RenderBlock*>::iterator end = containerSet->end();
for (HashSet<RenderBlock*>::iterator it = containerSet->begin(); it != end; ++it) {
RenderBlock* container = *it;
ASSERT(descendant->isDescendantOf(container));
TrackedRendererListHashSet* descendantSet = descendantsMap->get(container);
ASSERT(descendantSet);
if (!descendantSet)
continue;
ASSERT(descendantSet->contains(descendant));
descendantSet->remove(descendant);
if (descendantSet->isEmpty()) {
descendantsMap->remove(container);
delete descendantSet;
}
}
delete containerSet;
}
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)
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
if (!positionedDescendants)
return;
RenderBox* r;
TrackedRendererListHashSet::iterator end = positionedDescendants->end();
Vector<RenderBox*, 16> deadObjects;
for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
r = *it;
if (!o || r->isDescendantOf(o)) {
if (o)
r->setChildNeedsLayout(true, MarkOnlyThis);
RenderObject* p = r->parent();
while (p && !p->isRenderBlock())
p = p->parent();
if (p)
p->setChildNeedsLayout(true);
deadObjects.append(r);
}
}
for (unsigned i = 0; i < deadObjects.size(); i++)
removePositionedObject(deadObjects.at(i));
}
RenderBlock::FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
{
ASSERT(o->isFloating());
if (!m_floatingObjects)
m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
else {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
if (it != floatingObjectSet.end())
return *it;
}
FloatingObject* newObj = new FloatingObject(o->style()->floating());
bool isChildRenderBlock = o->isRenderBlock();
if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
o->setChildNeedsLayout(true, MarkOnlyThis);
bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) o->layoutIfNeeded();
else {
o->computeLogicalWidth();
o->computeBlockDirectionMargins(this);
}
setLogicalWidthForFloat(newObj, logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o));
newObj->setShouldPaint(!o->hasSelfPaintingLayer()); newObj->setIsDescendant(true);
newObj->m_renderer = o;
m_floatingObjects->add(newObj);
return newObj;
}
void RenderBlock::removeFloatingObject(RenderBox* o)
{
if (m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
if (it != floatingObjectSet.end()) {
FloatingObject* r = *it;
if (childrenInline()) {
LayoutUnit logicalTop = logicalTopForFloat(r);
LayoutUnit logicalBottom = logicalBottomForFloat(r);
if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == MAX_LAYOUT_UNIT)
logicalBottom = MAX_LAYOUT_UNIT;
else {
logicalBottom = max(logicalBottom, logicalTop + 1);
}
if (r->m_originatingLine) {
if (!selfNeedsLayout()) {
ASSERT(r->m_originatingLine->renderer() == this);
r->m_originatingLine->markDirty();
}
#if !ASSERT_DISABLED
r->m_originatingLine = 0;
#endif
}
markLinesDirtyInBlockRange(0, logicalBottom);
}
m_floatingObjects->remove(r);
ASSERT(!r->m_originatingLine);
delete r;
}
}
}
void RenderBlock::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
{
if (!m_floatingObjects)
return;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObject* curr = floatingObjectSet.last();
while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
m_floatingObjects->remove(curr);
ASSERT(!curr->m_originatingLine);
delete curr;
if (floatingObjectSet.isEmpty())
break;
curr = floatingObjectSet.last();
}
}
LayoutPoint RenderBlock::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
{
RenderBox* childBox = floatingObject->renderer();
LayoutUnit logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
LayoutUnit floatLogicalLeft;
if (childBox->style()->floating() == LeftFloat) {
LayoutUnit heightRemainingLeft = 1;
LayoutUnit heightRemainingRight = 1;
floatLogicalLeft = logicalLeftOffsetForLine(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
while (logicalRightOffsetForLine(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
floatLogicalLeft = logicalLeftOffsetForLine(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
if (inRenderFlowThread()) {
logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
}
}
floatLogicalLeft = max<LayoutUnit>(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
} else {
LayoutUnit heightRemainingLeft = 1;
LayoutUnit heightRemainingRight = 1;
floatLogicalLeft = logicalRightOffsetForLine(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
while (floatLogicalLeft - logicalLeftOffsetForLine(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
floatLogicalLeft = logicalRightOffsetForLine(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
if (inRenderFlowThread()) {
logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
}
}
floatLogicalLeft -= logicalWidthForFloat(floatingObject); }
return LayoutPoint(floatLogicalLeft, logicalTopOffset);
}
bool RenderBlock::positionNewFloats()
{
if (!m_floatingObjects)
return false;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
if (floatingObjectSet.isEmpty())
return false;
if (floatingObjectSet.last()->isPlaced())
return false;
FloatingObjectSetIterator it = floatingObjectSet.end();
--it; FloatingObjectSetIterator begin = floatingObjectSet.begin();
FloatingObject* lastPlacedFloatingObject = 0;
while (it != begin) {
--it;
if ((*it)->isPlaced()) {
lastPlacedFloatingObject = *it;
++it;
break;
}
}
LayoutUnit logicalTop = logicalHeight();
if (lastPlacedFloatingObject)
logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
FloatingObjectSetIterator end = floatingObjectSet.end();
for (; it != end; ++it) {
FloatingObject* floatingObject = *it;
if (floatingObject->renderer()->containingBlock() != this)
continue;
RenderBox* childBox = floatingObject->renderer();
LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
LayoutRect oldRect(childBox->x(), childBox->y() , childBox->width(), childBox->height());
if (childBox->style()->clear() & CLEFT)
logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
if (childBox->style()->clear() & CRIGHT)
logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
LayoutState* layoutState = view()->layoutState();
bool isPaginated = layoutState->isPaginated();
if (isPaginated && !childBox->needsLayout())
childBox->markForPaginationRelayoutIfNeeded();
childBox->layoutIfNeeded();
if (isPaginated) {
LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
if (childBlock && childBlock->paginationStrut()) {
newLogicalTop += childBlock->paginationStrut();
childBlock->setPaginationStrut(0);
}
if (newLogicalTop != floatLogicalLocation.y()) {
floatingObject->m_paginationStrut = newLogicalTop - floatLogicalLocation.y();
floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
if (childBlock)
childBlock->setChildNeedsLayout(true, MarkOnlyThis);
childBox->layoutIfNeeded();
}
}
setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
m_floatingObjects->addPlacedObject(floatingObject);
if (childBox->checkForRepaintDuringLayout())
childBox->repaintDuringLayoutIfMoved(oldRect);
}
return true;
}
void RenderBlock::newLine(EClear clear)
{
positionNewFloats();
LayoutUnit newY = 0;
switch (clear)
{
case CLEFT:
newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
break;
case CRIGHT:
newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
break;
case CBOTH:
newY = lowestFloatLogicalBottom();
default:
break;
}
if (height() < newY)
setLogicalHeight(newY);
}
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);
}
}
template <RenderBlock::FloatingObject::Type FloatTypeValue>
inline void RenderBlock::FloatIntervalSearchAdapter<FloatTypeValue>::collectIfNeeded(const IntervalType& interval) const
{
const FloatingObject* r = interval.data();
if (r->type() == FloatTypeValue && interval.low() <= m_value && m_value < interval.high()) {
ASSERT(r->isPlaced() && m_renderer->pixelSnappedLogicalTopForFloat(r) <= m_value && m_renderer->pixelSnappedLogicalBottomForFloat(r) > m_value);
if (FloatTypeValue == FloatingObject::FloatLeft
&& m_renderer->logicalRightForFloat(r) > m_offset) {
m_offset = m_renderer->logicalRightForFloat(r);
if (m_heightRemaining)
*m_heightRemaining = m_renderer->logicalBottomForFloat(r) - m_value;
}
if (FloatTypeValue == FloatingObject::FloatRight
&& m_renderer->logicalLeftForFloat(r) < m_offset) {
m_offset = m_renderer->logicalLeftForFloat(r);
if (m_heightRemaining)
*m_heightRemaining = m_renderer->logicalBottomForFloat(r) - m_value;
}
}
}
LayoutUnit RenderBlock::textIndentOffset() const
{
LayoutUnit cw = 0;
RenderView* renderView = 0;
if (style()->textIndent().isPercent())
cw = containingBlock()->availableLogicalWidth();
else if (style()->textIndent().isViewportPercentage())
renderView = view();
return minimumValueForLength(style()->textIndent(), cw, renderView);
}
LayoutUnit RenderBlock::logicalLeftOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
{
LayoutUnit logicalLeftOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
if (!inRenderFlowThread())
return logicalLeftOffset;
LayoutRect boxRect = borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage);
return logicalLeftOffset + (isHorizontalWritingMode() ? boxRect.x() : boxRect.y());
}
LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region, LayoutUnit offsetFromLogicalTopOfFirstPage) const
{
LayoutUnit logicalRightOffset = style()->isHorizontalWritingMode() ? borderLeft() + paddingLeft() : borderTop() + paddingTop();
logicalRightOffset += availableLogicalWidth();
if (!inRenderFlowThread())
return logicalRightOffset;
LayoutRect boxRect = borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage);
return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
}
LayoutUnit RenderBlock::logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
{
LayoutUnit left = fixedOffset;
if (m_floatingObjects && m_floatingObjects->hasLeftObjects()) {
if (heightRemaining)
*heightRemaining = 1;
FloatIntervalSearchAdapter<FloatingObject::FloatLeft> adapter(this, logicalTop, left, heightRemaining);
m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
}
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::logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
{
LayoutUnit right = fixedOffset;
if (m_floatingObjects && m_floatingObjects->hasRightObjects()) {
if (heightRemaining)
*heightRemaining = 1;
LayoutUnit rightFloatOffset = fixedOffset;
FloatIntervalSearchAdapter<FloatingObject::FloatRight> adapter(this, logicalTop, rightFloatOffset, heightRemaining);
m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
right = min(right, rightFloatOffset);
}
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;
}
LayoutUnit RenderBlock::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight) const
{
if (!m_floatingObjects)
return logicalHeight;
LayoutUnit bottom = MAX_LAYOUT_UNIT;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
LayoutUnit floatBottom = logicalBottomForFloat(r);
if (floatBottom > logicalHeight)
bottom = min(floatBottom, bottom);
}
return bottom == MAX_LAYOUT_UNIT ? ZERO_LAYOUT_UNIT : bottom;
}
LayoutUnit RenderBlock::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
{
if (!m_floatingObjects)
return 0;
LayoutUnit lowestFloatBottom = 0;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
if (r->isPlaced() && r->type() & floatType)
lowestFloatBottom = max(lowestFloatBottom, logicalBottomForFloat(r));
}
return lowestFloatBottom;
}
void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
{
if (logicalTop >= logicalBottom)
return;
RootInlineBox* lowestDirtyLine = lastRootBox();
RootInlineBox* afterLowest = lowestDirtyLine;
while (lowestDirtyLine && lowestDirtyLine->lineBottomWithLeading() >= logicalBottom && logicalBottom < MAX_LAYOUT_UNIT) {
afterLowest = lowestDirtyLine;
lowestDirtyLine = lowestDirtyLine->prevRootBox();
}
while (afterLowest && afterLowest != highest && (afterLowest->lineBottomWithLeading() >= logicalTop || afterLowest->lineBottomWithLeading() < 0)) {
afterLowest->markDirty();
afterLowest = afterLowest->prevRootBox();
}
}
void RenderBlock::clearFloats()
{
if (m_floatingObjects)
m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
HashSet<RenderBox*> oldIntrudingFloatSet;
if (!childrenInline() && m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* floatingObject = *it;
if (!floatingObject->isDescendant())
oldIntrudingFloatSet.add(floatingObject->m_renderer);
}
}
if (avoidsFloats() || isRoot() || isRenderView() || isFloatingOrOutOfFlowPositioned() || isTableCell()) {
if (m_floatingObjects) {
deleteAllValues(m_floatingObjects->set());
m_floatingObjects->clear();
}
if (!oldIntrudingFloatSet.isEmpty())
markAllDescendantsWithFloatsForLayout();
return;
}
typedef HashMap<RenderObject*, FloatingObject*> RendererToFloatInfoMap;
RendererToFloatInfoMap floatMap;
if (m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
if (childrenInline()) {
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* f = *it;
floatMap.add(f->m_renderer, f);
}
} else
deleteAllValues(floatingObjectSet);
m_floatingObjects->clear();
}
if (!parent() || !parent()->isRenderBlock())
return;
RenderBlock* parentBlock = toRenderBlock(parent());
bool parentHasFloats = false;
RenderObject* prev = previousSibling();
while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
if (prev->isFloating())
parentHasFloats = true;
prev = prev->previousSibling();
}
LayoutUnit logicalTopOffset = logicalTop();
if (parentHasFloats)
addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
LayoutUnit logicalLeftOffset = 0;
if (prev)
logicalTopOffset -= toRenderBox(prev)->logicalTop();
else {
prev = parentBlock;
logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
}
RenderBlock* block = toRenderBlock(prev);
if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
if (childrenInline()) {
LayoutUnit changeLogicalTop = MAX_LAYOUT_UNIT;
LayoutUnit changeLogicalBottom = MIN_LAYOUT_UNIT;
if (m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* f = *it;
FloatingObject* oldFloatingObject = floatMap.get(f->m_renderer);
LayoutUnit logicalBottom = logicalBottomForFloat(f);
if (oldFloatingObject) {
LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
if (logicalWidthForFloat(f) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(f) != logicalLeftForFloat(oldFloatingObject)) {
changeLogicalTop = 0;
changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
} else {
if (logicalBottom != oldLogicalBottom) {
changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
}
LayoutUnit logicalTop = logicalTopForFloat(f);
LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
if (logicalTop != oldLogicalTop) {
changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
}
}
floatMap.remove(f->m_renderer);
if (oldFloatingObject->m_originatingLine && !selfNeedsLayout()) {
ASSERT(oldFloatingObject->m_originatingLine->renderer() == this);
oldFloatingObject->m_originatingLine->markDirty();
}
delete oldFloatingObject;
} else {
changeLogicalTop = 0;
changeLogicalBottom = max(changeLogicalBottom, logicalBottom);
}
}
}
RendererToFloatInfoMap::iterator end = floatMap.end();
for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
FloatingObject* floatingObject = (*it).second;
if (!floatingObject->isDescendant()) {
changeLogicalTop = 0;
changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
}
}
deleteAllValues(floatMap);
markLinesDirtyInBlockRange(changeLogicalTop, changeLogicalBottom);
} else if (!oldIntrudingFloatSet.isEmpty()) {
if (m_floatingObjects->set().size() < oldIntrudingFloatSet.size())
markAllDescendantsWithFloatsForLayout();
else {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end && !oldIntrudingFloatSet.isEmpty(); ++it)
oldIntrudingFloatSet.remove((*it)->m_renderer);
if (!oldIntrudingFloatSet.isEmpty())
markAllDescendantsWithFloatsForLayout();
}
}
}
LayoutUnit RenderBlock::addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats)
{
if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
return 0;
LayoutUnit childLogicalTop = child->logicalTop();
LayoutUnit childLogicalLeft = child->logicalLeft();
LayoutUnit lowestFloatLogicalBottom = 0;
FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
FloatingObject* r = *childIt;
LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(r), MAX_LAYOUT_UNIT - childLogicalTop);
LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
if (logicalBottom > logicalHeight()) {
if (!containsFloat(r->m_renderer)) {
LayoutUnit leftOffset = isHorizontalWritingMode() ? -childLogicalLeft : -childLogicalTop;
LayoutUnit topOffset = isHorizontalWritingMode() ? -childLogicalTop : -childLogicalLeft;
FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->x() - leftOffset, r->y() - topOffset, r->width(), r->height()));
floatingObj->m_renderer = r->m_renderer;
if (r->m_renderer->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer())
r->setShouldPaint(false);
else
floatingObj->setShouldPaint(false);
floatingObj->setIsDescendant(true);
if (!m_floatingObjects)
m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
m_floatingObjects->add(floatingObj);
}
} else {
if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->m_renderer->hasSelfPaintingLayer()
&& r->m_renderer->isDescendantOf(child) && r->m_renderer->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
r->setShouldPaint(true);
}
if (r->isDescendant())
child->addOverflowFromChild(r->m_renderer, LayoutSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
}
}
return lowestFloatLogicalBottom;
}
bool RenderBlock::hasOverhangingFloat(RenderBox* renderer)
{
if (!m_floatingObjects || hasColumns() || !parent())
return false;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(renderer);
if (it == floatingObjectSet.end())
return false;
return logicalBottomForFloat(*it) > logicalHeight();
}
void RenderBlock::addIntrudingFloats(RenderBlock* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
{
if (!prev->m_floatingObjects)
return;
logicalLeftOffset += (isHorizontalWritingMode() ? marginLeft() : marginTop());
const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
FloatingObjectSetIterator prevEnd = prevSet.end();
for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
FloatingObject* r = *prevIt;
if (logicalBottomForFloat(r) > logicalTopOffset) {
if (!m_floatingObjects || !m_floatingObjects->set().contains(r)) {
LayoutUnit leftOffset = isHorizontalWritingMode() ? logicalLeftOffset : logicalTopOffset;
LayoutUnit topOffset = isHorizontalWritingMode() ? logicalTopOffset : logicalLeftOffset;
FloatingObject* floatingObj = new FloatingObject(r->type(), LayoutRect(r->x() - leftOffset, r->y() - topOffset, r->width(), r->height()));
if (prev != parent()) {
if (isHorizontalWritingMode())
floatingObj->setX(floatingObj->x() + prev->marginLeft());
else
floatingObj->setY(floatingObj->y() + prev->marginTop());
}
floatingObj->setShouldPaint(false); floatingObj->m_renderer = r->m_renderer;
if (!m_floatingObjects)
m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
m_floatingObjects->add(floatingObj);
}
}
}
}
bool RenderBlock::avoidsFloats() const
{
return RenderBox::avoidsFloats() || !style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth();
}
bool RenderBlock::containsFloat(RenderBox* renderer) const
{
return m_floatingObjects && m_floatingObjects->set().contains<RenderBox*, FloatingObjectHashTranslator>(renderer);
}
void RenderBlock::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
{
if (!everHadLayout())
return;
MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
setChildNeedsLayout(true, markParents);
if (floatToRemove)
removeFloatingObject(floatToRemove);
if (!childrenInline()) {
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
continue;
RenderBlock* childBlock = toRenderBlock(child);
if ((floatToRemove ? childBlock->containsFloat(floatToRemove) : childBlock->containsFloats()) || childBlock->shrinkToAvoidFloats())
childBlock->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
}
}
}
void RenderBlock::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
{
if (!m_floatingObjects)
return;
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
if (!next->isRenderBlock() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
continue;
RenderBlock* nextBlock = toRenderBlock(next);
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
RenderBox* floatingBox = (*it)->renderer();
if (floatToRemove && floatingBox != floatToRemove)
continue;
if (nextBlock->containsFloat(floatingBox))
nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
}
}
}
LayoutUnit RenderBlock::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
{
if (!containsFloats())
return 0;
bool clearSet = child->style()->clear() != CNONE;
LayoutUnit logicalBottom = 0;
switch (child->style()->clear()) {
case CNONE:
break;
case CLEFT:
logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
break;
case CRIGHT:
logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
break;
case CBOTH:
logicalBottom = lowestFloatLogicalBottom();
break;
}
LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : ZERO_LAYOUT_UNIT;
if (!result && child->avoidsFloats()) {
LayoutUnit newLogicalTop = logicalTop;
while (true) {
LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false);
if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
return newLogicalTop - logicalTop;
RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
LayoutRect borderBox = child->borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage() + logicalTopForChild(child), DoNotCacheRenderBoxRegionInfo);
LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
LayoutUnit childOldLogicalWidth = child->logicalWidth();
LayoutUnit childOldMarginLeft = child->marginLeft();
LayoutUnit childOldMarginRight = child->marginRight();
LayoutUnit childOldLogicalTop = child->logicalTop();
child->setLogicalTop(newLogicalTop);
child->computeLogicalWidth();
region = regionAtBlockOffset(logicalTopForChild(child));
borderBox = child->borderBoxRectInRegion(region, offsetFromLogicalTopOfFirstPage() + logicalTopForChild(child), DoNotCacheRenderBoxRegionInfo);
LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
child->setLogicalTop(childOldLogicalTop);
child->setLogicalWidth(childOldLogicalWidth);
child->setMarginLeft(childOldMarginLeft);
child->setMarginRight(childOldMarginRight);
if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
child->setChildNeedsLayout(true, MarkOnlyThis);
return newLogicalTop - logicalTop;
}
newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
ASSERT(newLogicalTop >= logicalTop);
if (newLogicalTop < logicalTop)
break;
}
ASSERT_NOT_REACHED();
}
return result;
}
bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset)
{
if (!scrollsOverflow())
return false;
return layer()->hitTestOverflowControls(result, roundedIntPoint(pointInContainer - toLayoutSize(accumulatedOffset)));
}
bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
LayoutPoint adjustedLocation(accumulatedOffset + location());
LayoutSize localOffset = toLayoutSize(adjustedLocation);
if (!isRenderView()) {
LayoutRect overflowBox = visualOverflowRect();
flipForWritingMode(overflowBox);
overflowBox.moveBy(adjustedLocation);
if (!overflowBox.intersects(result.rectForPoint(pointInContainer)))
return false;
}
if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && isPointInOverflowControl(result, pointInContainer, adjustedLocation)) {
updateHitTestResult(result, pointInContainer - localOffset);
if (!result.addNodeToRectBasedTestResult(node(), pointInContainer))
return true;
}
bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
bool useClip = (hasControlClip() || useOverflowClip);
LayoutRect hitTestArea(result.rectForPoint(pointInContainer));
bool checkChildren = !useClip || (hasControlClip() ? controlClipRect(adjustedLocation).intersects(hitTestArea) : overflowClipRect(adjustedLocation, result.region(), IncludeOverlayScrollbarSize).intersects(hitTestArea));
if (checkChildren) {
LayoutSize scrolledOffset(localOffset);
if (hasOverflowClip())
scrolledOffset -= scrolledContentOffset();
if (!hasColumns()) {
if (hitTestContents(request, result, pointInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
updateHitTestResult(result, pointInContainer - localOffset);
return true;
}
if (hitTestAction == HitTestFloat && hitTestFloats(request, result, pointInContainer, toLayoutPoint(scrolledOffset)))
return true;
} else if (hitTestColumns(request, result, pointInContainer, toLayoutPoint(scrolledOffset), hitTestAction)) {
updateHitTestResult(result, flipForWritingMode(pointInContainer - localOffset));
return true;
}
}
if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
LayoutRect boundsRect(adjustedLocation, size());
if (visibleToHitTesting() && boundsRect.intersects(result.rectForPoint(pointInContainer))) {
updateHitTestResult(result, flipForWritingMode(pointInContainer - localOffset));
if (!result.addNodeToRectBasedTestResult(node(), pointInContainer, boundsRect))
return true;
}
}
return false;
}
bool RenderBlock::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset)
{
if (!m_floatingObjects)
return false;
LayoutPoint adjustedLocation = accumulatedOffset;
if (isRenderView()) {
adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
}
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator begin = floatingObjectSet.begin();
for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
--it;
FloatingObject* floatingObject = *it;
if (floatingObject->shouldPaint() && !floatingObject->m_renderer->hasSelfPaintingLayer()) {
LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->m_renderer->x();
LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->m_renderer->y();
LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
if (floatingObject->m_renderer->hitTest(request, result, pointInContainer, childPoint)) {
updateHitTestResult(result, pointInContainer - toLayoutSize(childPoint));
return true;
}
}
}
return false;
}
class ColumnRectIterator {
WTF_MAKE_NONCOPYABLE(ColumnRectIterator);
public:
ColumnRectIterator(const RenderBlock& block)
: m_block(block)
, m_colInfo(block.columnInfo())
, m_direction(m_block.style()->isFlippedBlocksWritingMode() ? 1 : -1)
, m_isHorizontal(block.isHorizontalWritingMode())
, m_logicalLeft(block.logicalLeftOffsetForContent())
{
int colCount = m_colInfo->columnCount();
m_colIndex = colCount - 1;
m_currLogicalTopOffset = colCount * m_colInfo->columnHeight() * m_direction;
update();
}
void advance()
{
ASSERT(hasMore());
m_colIndex--;
update();
}
LayoutRect columnRect() const { return m_colRect; }
bool hasMore() const { return m_colIndex >= 0; }
void adjust(LayoutSize& offset) const
{
LayoutUnit currLogicalLeftOffset = (m_isHorizontal ? m_colRect.x() : m_colRect.y()) - m_logicalLeft;
offset += m_isHorizontal ? LayoutSize(currLogicalLeftOffset, m_currLogicalTopOffset) : LayoutSize(m_currLogicalTopOffset, currLogicalLeftOffset);
if (m_colInfo->progressionAxis() == ColumnInfo::BlockAxis) {
if (m_isHorizontal)
offset.expand(0, m_colRect.y() - m_block.borderTop() - m_block.paddingTop());
else
offset.expand(m_colRect.x() - m_block.borderLeft() - m_block.paddingLeft(), 0);
}
}
private:
void update()
{
if (m_colIndex < 0)
return;
m_colRect = m_block.columnRectAt(const_cast<ColumnInfo*>(m_colInfo), m_colIndex);
m_block.flipForWritingMode(m_colRect);
m_currLogicalTopOffset -= (m_isHorizontal ? m_colRect.height() : m_colRect.width()) * m_direction;
}
const RenderBlock& m_block;
const ColumnInfo* const m_colInfo;
const int m_direction;
const bool m_isHorizontal;
const LayoutUnit m_logicalLeft;
int m_colIndex;
LayoutUnit m_currLogicalTopOffset;
LayoutRect m_colRect;
};
bool RenderBlock::hitTestColumns(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
if (!hasColumns())
return false;
for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
LayoutRect hitRect = result.rectForPoint(pointInContainer);
LayoutRect colRect = it.columnRect();
colRect.moveBy(accumulatedOffset);
if (colRect.intersects(hitRect)) {
LayoutSize offset;
it.adjust(offset);
LayoutPoint finalLocation = accumulatedOffset + offset;
if (!result.isRectBasedTest() || colRect.contains(hitRect))
return hitTestContents(request, result, pointInContainer, finalLocation, hitTestAction) || (hitTestAction == HitTestFloat && hitTestFloats(request, result, pointInContainer, finalLocation));
hitTestContents(request, result, pointInContainer, finalLocation, hitTestAction);
}
}
return false;
}
void RenderBlock::adjustForColumnRect(LayoutSize& offset, const LayoutPoint& pointInContainer) const
{
for (ColumnRectIterator it(*this); it.hasMore(); it.advance()) {
LayoutRect colRect = it.columnRect();
if (colRect.contains(pointInContainer)) {
it.adjust(offset);
return;
}
}
}
bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
if (childrenInline() && !isTable()) {
if (m_lineBoxes.hitTest(this, request, result, pointInContainer, accumulatedOffset, hitTestAction))
return true;
} else {
HitTestAction childHitTest = hitTestAction;
if (hitTestAction == HitTestChildBlockBackgrounds)
childHitTest = HitTestChildBlockBackground;
for (RenderBox* child = lastChildBox(); child; child = child->previousSiblingBox()) {
LayoutPoint childPoint = flipForWritingModeForChild(child, accumulatedOffset);
if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, pointInContainer, childPoint, childHitTest))
return true;
}
}
return false;
}
Position RenderBlock::positionForBox(InlineBox *box, bool start) const
{
if (!box)
return Position();
if (!box->renderer()->node())
return createLegacyEditingPosition(node(), start ? caretMinOffset() : caretMaxOffset());
if (!box->isInlineTextBox())
return createLegacyEditingPosition(box->renderer()->node(), start ? box->renderer()->caretMinOffset() : box->renderer()->caretMaxOffset());
InlineTextBox* textBox = toInlineTextBox(box);
return createLegacyEditingPosition(box->renderer()->node(), start ? textBox->start() : textBox->start() + textBox->len());
}
static inline bool isEditingBoundary(RenderObject* ancestor, RenderObject* child)
{
ASSERT(!ancestor || ancestor->node());
ASSERT(child && child->node());
return !ancestor || !ancestor->parent() || (ancestor->hasLayer() && ancestor->parent()->isRenderView())
|| ancestor->node()->rendererIsEditable() == child->node()->rendererIsEditable();
}
static VisiblePosition positionForPointRespectingEditingBoundaries(RenderBlock* parent, RenderBox* child, const LayoutPoint& pointInParentCoordinates)
{
LayoutPoint childLocation = child->location();
if (child->isInFlowPositioned())
childLocation += child->offsetForInFlowPosition();
LayoutPoint pointInChildCoordinates(toLayoutPoint(pointInParentCoordinates - childLocation));
Node* childNode = child->node();
if (!childNode)
return child->positionForPoint(pointInChildCoordinates);
RenderObject* ancestor = parent;
while (ancestor && !ancestor->node())
ancestor = ancestor->parent();
if (isEditingBoundary(ancestor, child))
return child->positionForPoint(pointInChildCoordinates);
if (childNode->isContentEditable() && !ancestor->node()->isContentEditable())
return child->positionForPoint(pointInChildCoordinates);
LayoutUnit childMiddle = parent->logicalWidthForChild(child) / 2;
LayoutUnit logicalLeft = parent->isHorizontalWritingMode() ? pointInChildCoordinates.x() : pointInChildCoordinates.y();
if (logicalLeft < childMiddle)
return ancestor->createVisiblePosition(childNode->nodeIndex(), DOWNSTREAM);
return ancestor->createVisiblePosition(childNode->nodeIndex() + 1, UPSTREAM);
}
VisiblePosition RenderBlock::positionForPointWithInlineChildren(const LayoutPoint& pointInLogicalContents)
{
ASSERT(childrenInline());
if (!firstRootBox())
return createVisiblePosition(0, DOWNSTREAM);
bool linesAreFlipped = style()->isFlippedLinesWritingMode();
bool blocksAreFlipped = style()->isFlippedBlocksWritingMode();
InlineBox* closestBox = 0;
RootInlineBox* firstRootBoxWithChildren = 0;
RootInlineBox* lastRootBoxWithChildren = 0;
for (RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox()) {
if (!root->firstLeafChild())
continue;
if (!firstRootBoxWithChildren)
firstRootBoxWithChildren = root;
if (!linesAreFlipped && root->isFirstAfterPageBreak() && (pointInLogicalContents.y() < root->lineTopWithLeading()
|| (blocksAreFlipped && pointInLogicalContents.y() == root->lineTopWithLeading())))
break;
lastRootBoxWithChildren = root;
if (pointInLogicalContents.y() < root->selectionBottom() || (blocksAreFlipped && pointInLogicalContents.y() == root->selectionBottom())) {
if (linesAreFlipped) {
RootInlineBox* nextRootBoxWithChildren = root->nextRootBox();
while (nextRootBoxWithChildren && !nextRootBoxWithChildren->firstLeafChild())
nextRootBoxWithChildren = nextRootBoxWithChildren->nextRootBox();
if (nextRootBoxWithChildren && nextRootBoxWithChildren->isFirstAfterPageBreak() && (pointInLogicalContents.y() > nextRootBoxWithChildren->lineTopWithLeading()
|| (!blocksAreFlipped && pointInLogicalContents.y() == nextRootBoxWithChildren->lineTopWithLeading())))
continue;
}
closestBox = root->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
if (closestBox)
break;
}
}
bool moveCaretToBoundary = !document()->frame()->singleLineSelectionBehavior();
if (!moveCaretToBoundary && !closestBox && lastRootBoxWithChildren) {
closestBox = lastRootBoxWithChildren->closestLeafChildForLogicalLeftPosition(pointInLogicalContents.x());
}
if (closestBox) {
if (moveCaretToBoundary) {
LayoutUnit firstRootBoxWithChildrenTop = min<LayoutUnit>(firstRootBoxWithChildren->selectionTop(), firstRootBoxWithChildren->logicalTop());
if (pointInLogicalContents.y() < firstRootBoxWithChildrenTop
|| (blocksAreFlipped && pointInLogicalContents.y() == firstRootBoxWithChildrenTop)) {
InlineBox* box = firstRootBoxWithChildren->firstLeafChild();
if (box->isLineBreak()) {
if (InlineBox* newBox = box->nextLeafChildIgnoringLineBreak())
box = newBox;
}
return VisiblePosition(positionForBox(box, true), DOWNSTREAM);
}
}
LayoutPoint point(pointInLogicalContents.x(), closestBox->root()->blockDirectionPointInLine());
if (!isHorizontalWritingMode())
point = point.transposedPoint();
if (closestBox->renderer()->isReplaced())
return positionForPointRespectingEditingBoundaries(this, toRenderBox(closestBox->renderer()), point);
return closestBox->renderer()->positionForPoint(point);
}
if (lastRootBoxWithChildren) {
ASSERT(moveCaretToBoundary);
InlineBox* logicallyLastBox;
if (lastRootBoxWithChildren->getLogicalEndBoxWithNode(logicallyLastBox))
return VisiblePosition(positionForBox(logicallyLastBox, false), DOWNSTREAM);
}
return createVisiblePosition(0, DOWNSTREAM);
}
static inline bool isChildHitTestCandidate(RenderBox* box)
{
return box->height() && box->style()->visibility() == VISIBLE && !box->isFloatingOrOutOfFlowPositioned();
}
VisiblePosition RenderBlock::positionForPoint(const LayoutPoint& point)
{
if (isTable())
return RenderBox::positionForPoint(point);
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);
RenderBox* lastCandidateBox = lastChildBox();
while (lastCandidateBox && !isChildHitTestCandidate(lastCandidateBox))
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 (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
if (!isChildHitTestCandidate(childBox))
continue;
LayoutUnit childLogicalBottom = logicalTopForChild(childBox) + logicalHeightForChild(childBox);
if (isChildHitTestCandidate(childBox) && (pointInLogicalContents.y() < childLogicalBottom
|| (blocksAreFlipped && pointInLogicalContents.y() == childLogicalBottom)))
return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
}
}
return RenderBox::positionForPoint(point);
}
void RenderBlock::offsetForContents(LayoutPoint& offset) const
{
offset = flipForWritingMode(offset);
if (hasOverflowClip())
offset += scrolledContentOffset();
if (hasColumns())
adjustPointToColumnContents(offset);
offset = flipForWritingMode(offset);
}
LayoutUnit RenderBlock::availableLogicalWidth() const
{
if (hasColumns())
return desiredColumnWidth();
return RenderBox::availableLogicalWidth();
}
int RenderBlock::columnGap() const
{
if (style()->hasNormalColumnGap())
return style()->fontDescription().computedPixelSize(); return static_cast<int>(style()->columnGap());
}
void RenderBlock::calcColumnWidth()
{
if (document()->regionBasedColumnsEnabled())
return;
unsigned desiredColumnCount = 1;
LayoutUnit desiredColumnWidth = contentLogicalWidth();
if (document()->paginated() || (style()->hasAutoColumnCount() && style()->hasAutoColumnWidth()) || !style()->hasInlineColumnAxis()) {
setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
return;
}
LayoutUnit availWidth = desiredColumnWidth;
LayoutUnit colGap = columnGap();
LayoutUnit colWidth = max<LayoutUnit>(1, LayoutUnit(style()->columnWidth()));
int colCount = max<int>(1, style()->columnCount());
if (style()->hasAutoColumnWidth() && !style()->hasAutoColumnCount()) {
desiredColumnCount = colCount;
desiredColumnWidth = max<LayoutUnit>(0, (availWidth - ((desiredColumnCount - 1) * colGap)) / desiredColumnCount);
} else if (!style()->hasAutoColumnWidth() && style()->hasAutoColumnCount()) {
desiredColumnCount = max<LayoutUnit>(1, (availWidth + colGap) / (colWidth + colGap));
desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
} else {
desiredColumnCount = max<LayoutUnit>(min<LayoutUnit>(colCount, (availWidth + colGap) / (colWidth + colGap)), 1);
desiredColumnWidth = ((availWidth + colGap) / desiredColumnCount) - colGap;
}
setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
}
bool RenderBlock::requiresColumns(int desiredColumnCount) const
{
return firstChild()
&& (desiredColumnCount != 1 || !style()->hasAutoColumnWidth() || !style()->hasInlineColumnAxis())
&& !firstChild()->isAnonymousColumnsBlock()
&& !firstChild()->isAnonymousColumnSpanBlock();
}
void RenderBlock::setDesiredColumnCountAndWidth(int count, LayoutUnit width)
{
bool destroyColumns = !requiresColumns(count);
if (destroyColumns) {
if (hasColumns()) {
delete gColumnInfoMap->take(this);
setHasColumns(false);
}
} else {
ColumnInfo* info;
if (hasColumns())
info = gColumnInfoMap->get(this);
else {
if (!gColumnInfoMap)
gColumnInfoMap = new ColumnInfoMap;
info = new ColumnInfo;
gColumnInfoMap->add(this, info);
setHasColumns(true);
}
info->setDesiredColumnCount(count);
info->setDesiredColumnWidth(width);
info->setProgressionAxis(style()->hasInlineColumnAxis() ? ColumnInfo::InlineAxis : ColumnInfo::BlockAxis);
info->setProgressionIsReversed(style()->columnProgression() == ReverseColumnProgression);
}
}
LayoutUnit RenderBlock::desiredColumnWidth() const
{
if (!hasColumns())
return contentLogicalWidth();
return gColumnInfoMap->get(this)->desiredColumnWidth();
}
unsigned RenderBlock::desiredColumnCount() const
{
if (!hasColumns())
return 1;
return gColumnInfoMap->get(this)->desiredColumnCount();
}
ColumnInfo* RenderBlock::columnInfo() const
{
if (!hasColumns())
return 0;
return gColumnInfoMap->get(this);
}
unsigned RenderBlock::columnCount(ColumnInfo* colInfo) const
{
ASSERT(hasColumns());
ASSERT(gColumnInfoMap->get(this) == colInfo);
return colInfo->columnCount();
}
LayoutRect RenderBlock::columnRectAt(ColumnInfo* colInfo, unsigned index) const
{
ASSERT(hasColumns() && gColumnInfoMap->get(this) == colInfo);
LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
LayoutUnit colLogicalHeight = colInfo->columnHeight();
LayoutUnit colLogicalTop = borderBefore() + paddingBefore();
LayoutUnit colLogicalLeft = logicalLeftOffsetForContent();
int colGap = columnGap();
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
if (style()->isLeftToRightDirection() ^ colInfo->progressionIsReversed())
colLogicalLeft += index * (colLogicalWidth + colGap);
else
colLogicalLeft += contentLogicalWidth() - colLogicalWidth - index * (colLogicalWidth + colGap);
} else {
if (!colInfo->progressionIsReversed())
colLogicalTop += index * (colLogicalHeight + colGap);
else
colLogicalTop += contentLogicalHeight() - colLogicalHeight - index * (colLogicalHeight + colGap);
}
if (isHorizontalWritingMode())
return LayoutRect(colLogicalLeft, colLogicalTop, colLogicalWidth, colLogicalHeight);
return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
}
bool RenderBlock::layoutColumns(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer& statePusher)
{
if (!hasColumns())
return false;
OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
if (childrenInline())
addOverflowFromInlineChildren();
else
addOverflowFromBlockChildren();
LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
ColumnInfo* colInfo = columnInfo();
if (!hasSpecifiedPageLogicalHeight) {
LayoutUnit columnHeight = pageLogicalHeight;
int minColumnCount = colInfo->forcedBreaks() + 1;
int desiredColumnCount = colInfo->desiredColumnCount();
if (minColumnCount >= desiredColumnCount) {
if (!pageLogicalHeight) {
LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
}
} else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
}
if (columnHeight && columnHeight != pageLogicalHeight) {
statePusher.pop();
setEverHadLayout(true);
layoutBlock(false, columnHeight);
return true;
}
}
if (pageLogicalHeight)
colInfo->setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
if (columnCount(colInfo)) {
setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
m_overflow.clear();
} else
m_overflow = savedOverflow.release();
return false;
}
void RenderBlock::adjustPointToColumnContents(LayoutPoint& point) const
{
if (!hasColumns())
return;
ColumnInfo* colInfo = columnInfo();
if (!columnCount(colInfo))
return;
LayoutUnit colGap = columnGap();
LayoutUnit halfColGap = colGap / 2;
LayoutPoint columnPoint(columnRectAt(colInfo, 0).location());
LayoutUnit logicalOffset = 0;
for (unsigned i = 0; i < colInfo->columnCount(); i++) {
LayoutRect colRect = columnRectAt(colInfo, i);
flipForWritingMode(colRect);
if (isHorizontalWritingMode() == (colInfo->progressionAxis() == ColumnInfo::InlineAxis)) {
LayoutRect gapAndColumnRect(colRect.x() - halfColGap, colRect.y(), colRect.width() + colGap, colRect.height());
if (point.x() >= gapAndColumnRect.x() && point.x() < gapAndColumnRect.maxX()) {
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
if (point.y() < gapAndColumnRect.y())
point = gapAndColumnRect.location();
else if (point.y() >= gapAndColumnRect.maxY()) {
point = gapAndColumnRect.location();
point.move(0, gapAndColumnRect.height());
}
} else {
if (point.x() < colRect.x())
point.setX(colRect.x());
else if (point.x() >= colRect.maxX())
point.setX(colRect.maxX() - 1);
}
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
point.move(columnPoint.x() - colRect.x(), (!style()->isFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset));
else
point.move((!style()->isFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.x() + borderLeft() + paddingLeft(), 0);
return;
}
logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.height() : colRect.width();
} else {
LayoutRect gapAndColumnRect(colRect.x(), colRect.y() - halfColGap, colRect.width(), colRect.height() + colGap);
if (point.y() >= gapAndColumnRect.y() && point.y() < gapAndColumnRect.maxY()) {
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
if (point.x() < gapAndColumnRect.x())
point = gapAndColumnRect.location();
else if (point.x() >= gapAndColumnRect.maxX()) {
point = gapAndColumnRect.location();
point.move(gapAndColumnRect.width(), 0);
}
} else {
if (point.y() < colRect.y())
point.setY(colRect.y());
else if (point.y() >= colRect.maxY())
point.setY(colRect.maxY() - 1);
}
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
point.move((!style()->isFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset), columnPoint.y() - colRect.y());
else
point.move(0, (!style()->isFlippedBlocksWritingMode() ? logicalOffset : -logicalOffset) - colRect.y() + borderTop() + paddingTop());
return;
}
logicalOffset += colInfo->progressionAxis() == ColumnInfo::InlineAxis ? colRect.width() : colRect.height();
}
}
}
void RenderBlock::adjustRectForColumns(LayoutRect& r) const
{
if (!hasColumns())
return;
ColumnInfo* colInfo = columnInfo();
unsigned colCount = columnCount(colInfo);
if (!colCount)
return;
LayoutRect result;
bool isHorizontal = isHorizontalWritingMode();
LayoutUnit beforeBorderPadding = borderBefore() + paddingBefore();
LayoutUnit colHeight = colInfo->columnHeight();
if (!colHeight)
return;
LayoutUnit startOffset = max(isHorizontal ? r.y() : r.x(), beforeBorderPadding);
LayoutUnit endOffset = min<LayoutUnit>(isHorizontal ? r.maxY() : r.maxX(), beforeBorderPadding + colCount * colHeight);
unsigned startColumn = (startOffset - beforeBorderPadding) / colHeight;
unsigned endColumn = (endOffset - beforeBorderPadding) / colHeight;
if (startColumn == endColumn) {
LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent();
LayoutRect colRect = columnRectAt(colInfo, startColumn);
LayoutRect repaintRect = r;
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis) {
if (isHorizontal)
repaintRect.move(colRect.x() - logicalLeftOffset, - static_cast<int>(startColumn) * colHeight);
else
repaintRect.move(- static_cast<int>(startColumn) * colHeight, colRect.y() - logicalLeftOffset);
} else {
if (isHorizontal)
repaintRect.move(0, colRect.y() - startColumn * colHeight - beforeBorderPadding);
else
repaintRect.move(colRect.x() - startColumn * colHeight - beforeBorderPadding, 0);
}
repaintRect.intersect(colRect);
result.unite(repaintRect);
} else {
result.unite(columnRectAt(colInfo, startColumn));
result.unite(columnRectAt(colInfo, endColumn));
}
r = result;
}
LayoutPoint RenderBlock::flipForWritingModeIncludingColumns(const LayoutPoint& point) const
{
ASSERT(hasColumns());
if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
return point;
ColumnInfo* colInfo = columnInfo();
LayoutUnit columnLogicalHeight = colInfo->columnHeight();
LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
if (isHorizontalWritingMode())
return LayoutPoint(point.x(), expandedLogicalHeight - point.y());
return LayoutPoint(expandedLogicalHeight - point.x(), point.y());
}
void RenderBlock::adjustStartEdgeForWritingModeIncludingColumns(LayoutRect& rect) const
{
ASSERT(hasColumns());
if (!hasColumns() || !style()->isFlippedBlocksWritingMode())
return;
ColumnInfo* colInfo = columnInfo();
LayoutUnit columnLogicalHeight = colInfo->columnHeight();
LayoutUnit expandedLogicalHeight = borderBefore() + paddingBefore() + columnCount(colInfo) * columnLogicalHeight + borderAfter() + paddingAfter() + scrollbarLogicalHeight();
if (isHorizontalWritingMode())
rect.setY(expandedLogicalHeight - rect.maxY());
else
rect.setX(expandedLogicalHeight - rect.maxX());
}
void RenderBlock::adjustForColumns(LayoutSize& offset, const LayoutPoint& point) const
{
if (!hasColumns())
return;
ColumnInfo* colInfo = columnInfo();
LayoutUnit logicalLeft = logicalLeftOffsetForContent();
unsigned colCount = columnCount(colInfo);
LayoutUnit colLogicalWidth = colInfo->desiredColumnWidth();
LayoutUnit colLogicalHeight = colInfo->columnHeight();
for (unsigned i = 0; i < colCount; ++i) {
LayoutRect sliceRect = LayoutRect(logicalLeft, borderBefore() + paddingBefore() + i * colLogicalHeight, colLogicalWidth, colLogicalHeight);
if (!isHorizontalWritingMode())
sliceRect = sliceRect.transposedRect();
LayoutUnit logicalOffset = i * colLogicalHeight;
if (isHorizontalWritingMode()) {
if (point.y() >= sliceRect.y() && point.y() < sliceRect.maxY()) {
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
offset.expand(columnRectAt(colInfo, i).x() - logicalLeft, -logicalOffset);
else
offset.expand(0, columnRectAt(colInfo, i).y() - logicalOffset - borderBefore() - paddingBefore());
return;
}
} else {
if (point.x() >= sliceRect.x() && point.x() < sliceRect.maxX()) {
if (colInfo->progressionAxis() == ColumnInfo::InlineAxis)
offset.expand(-logicalOffset, columnRectAt(colInfo, i).y() - logicalLeft);
else
offset.expand(columnRectAt(colInfo, i).x() - logicalOffset - borderBefore() - paddingBefore(), 0);
return;
}
}
}
}
void RenderBlock::computePreferredLogicalWidths()
{
ASSERT(preferredLogicalWidthsDirty());
updateFirstLetter();
RenderStyle* styleToUse = style();
if (!isTableCell() && styleToUse->logicalWidth().isFixed() && styleToUse->logicalWidth().value() > 0 && style()->marqueeBehavior() != MALTERNATE)
m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = computeContentBoxLogicalWidth(styleToUse->logicalWidth().value());
else {
m_minPreferredLogicalWidth = 0;
m_maxPreferredLogicalWidth = 0;
if (childrenInline())
computeInlinePreferredLogicalWidths();
else
computeBlockPreferredLogicalWidths();
m_maxPreferredLogicalWidth = max(m_minPreferredLogicalWidth, m_maxPreferredLogicalWidth);
if (!styleToUse->autoWrap() && childrenInline()) {
m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth;
if (layer() && layer()->marquee() && layer()->marquee()->isHorizontal())
m_minPreferredLogicalWidth = 0;
}
int scrollbarWidth = 0;
if (hasOverflowClip() && styleToUse->overflowY() == OSCROLL) {
layer()->setHasVerticalScrollbar(true);
scrollbarWidth = verticalScrollbarWidth();
m_maxPreferredLogicalWidth += scrollbarWidth;
}
if (isTableCell()) {
Length w = toRenderTableCell(this)->styleOrColLogicalWidth();
if (w.isFixed() && w.value() > 0) {
m_maxPreferredLogicalWidth = max(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(w.value()));
scrollbarWidth = 0;
}
}
m_minPreferredLogicalWidth += scrollbarWidth;
}
if (styleToUse->logicalMinWidth().isFixed() && styleToUse->logicalMinWidth().value() > 0) {
m_maxPreferredLogicalWidth = max(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMinWidth().value()));
m_minPreferredLogicalWidth = max(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMinWidth().value()));
}
if (styleToUse->logicalMaxWidth().isFixed()) {
m_maxPreferredLogicalWidth = min(m_maxPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMaxWidth().value()));
m_minPreferredLogicalWidth = min(m_minPreferredLogicalWidth, computeContentBoxLogicalWidth(styleToUse->logicalMaxWidth().value()));
}
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->firstChild();
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->isText() || result->isFloating() || result->isReplaced() || result->isRenderInline()))
break;
current = result;
result = 0;
}
current = result;
return current;
}
static int getBPMWidth(int childValue, Length cssUnit)
{
if (cssUnit.type() != Auto)
return (cssUnit.isFixed() ? cssUnit.value() : childValue);
return 0;
}
static int getBorderPaddingMargin(const RenderBoxModelObject* child, bool endOfInline)
{
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 = ceilf(result);
preferredWidth = max(snappedResult, preferredWidth);
}
void RenderBlock::computeInlinePreferredLogicalWidths()
{
float inlineMax = 0;
float inlineMin = 0;
RenderStyle* styleToUse = style();
RenderBlock* containingBlock = this->containingBlock();
LayoutUnit cw = containingBlock ? containingBlock->contentLogicalWidth() : ZERO_LAYOUT_UNIT;
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; RenderObject* prevFloat = 0;
while (RenderObject* child = childIterator.next()) {
autoWrap = child->isReplaced() ? child->parent()->style()->autoWrap() :
child->style()->autoWrap();
if (!child->isBR()) {
RenderStyle* childStyle = child->style();
float childMin = 0;
float childMax = 0;
if (!child->isText()) {
if (child->isRenderInline()) {
float bpm = getBorderPaddingMargin(toRenderInline(child), childIterator.endOfInline);
childMin += bpm;
childMax += bpm;
inlineMin += childMin;
inlineMax += childMax;
child->setPreferredLogicalWidthsDirty(false);
} else {
float margins = 0;
Length startMargin = childStyle->marginStart();
Length endMargin = childStyle->marginEnd();
if (startMargin.isFixed())
margins += startMargin.value();
if (endMargin.isFixed())
margins += endMargin.value();
childMin += margins;
childMax += margins;
}
}
if (!child->isRenderInline() && !child->isText()) {
childMin += child->minPreferredLogicalWidth();
childMax += child->maxPreferredLogicalWidth();
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)) || clearPreviousFloat) {
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
inlineMin = 0;
}
if (clearPreviousFloat) {
updatePreferredWidth(m_maxPreferredLogicalWidth, inlineMax);
inlineMax = 0;
}
LayoutUnit ti = 0;
if (!addedTextIndent) {
addedTextIndent = true;
ti = minimumValueForLength(styleToUse->textIndent(), cw, view());
childMin += ti;
childMax += ti;
}
inlineMax += childMax;
if (!autoWrap || !canBreakReplacedElement) {
if (child->isFloating())
updatePreferredWidth(m_minPreferredLogicalWidth, childMin);
else
inlineMin += childMin;
} else {
updatePreferredWidth(m_minPreferredLogicalWidth, childMin);
inlineMin = 0;
}
if (!child->isFloating()) {
stripFrontSpaces = false;
trailingSpaceChild = 0;
}
} else if (child->isText()) {
RenderText* t = toRenderText(child);
if (t->isWordBreak()) {
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
inlineMin = 0;
continue;
}
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(m_minPreferredLogicalWidth, inlineMin);
inlineMin = 0;
}
continue;
}
if (stripFrontSpaces)
trailingSpaceChild = child;
else
trailingSpaceChild = 0;
LayoutUnit ti = 0;
if (!addedTextIndent) {
addedTextIndent = true;
ti = minimumValueForLength(styleToUse->textIndent(), cw, view());
childMin+=ti; beginMin += ti;
childMax+=ti; beginMax += ti;
}
if (!hasBreakableChar) {
inlineMin += childMin;
} else {
if (beginWS)
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
else {
inlineMin += beginMin;
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
childMin -= ti;
}
inlineMin = childMin;
if (endWS) {
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
inlineMin = 0;
} else {
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
inlineMin = endMin;
}
}
if (hasBreak) {
inlineMax += beginMax;
updatePreferredWidth(m_maxPreferredLogicalWidth, inlineMax);
updatePreferredWidth(m_maxPreferredLogicalWidth, childMax);
inlineMax = endMax;
} else
inlineMax += childMax;
}
if (child->isListMarker())
stripFrontSpaces = true;
} else {
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
updatePreferredWidth(m_maxPreferredLogicalWidth, inlineMax);
inlineMin = inlineMax = 0;
stripFrontSpaces = true;
trailingSpaceChild = 0;
}
oldAutoWrap = autoWrap;
}
if (styleToUse->collapseWhiteSpace())
stripTrailingSpace(inlineMax, inlineMin, trailingSpaceChild);
updatePreferredWidth(m_minPreferredLogicalWidth, inlineMin);
updatePreferredWidth(m_maxPreferredLogicalWidth, inlineMax);
}
void RenderBlock::computeBlockPreferredLogicalWidths()
{
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;
}
RenderStyle* childStyle = child->style();
if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
LayoutUnit floatTotalWidth = floatLeftWidth + floatRightWidth;
if (childStyle->clear() & CLEFT) {
m_maxPreferredLogicalWidth = max(floatTotalWidth, m_maxPreferredLogicalWidth);
floatLeftWidth = 0;
}
if (childStyle->clear() & CRIGHT) {
m_maxPreferredLogicalWidth = max(floatTotalWidth, m_maxPreferredLogicalWidth);
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);
LayoutUnit oldHeight = childBox->logicalHeight();
childBox->setLogicalHeight(childBox->borderAndPaddingLogicalHeight());
childBox->computeLogicalHeight();
childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = childBox->logicalHeight();
childBox->setLogicalHeight(oldHeight);
} else {
childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
}
LayoutUnit w = childMinPreferredLogicalWidth + margin;
m_minPreferredLogicalWidth = max(w, m_minPreferredLogicalWidth);
if (nowrap && !child->isTable())
m_maxPreferredLogicalWidth = max(w, m_maxPreferredLogicalWidth);
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 ? max(floatLeftWidth, marginLogicalLeft) : floatLeftWidth + marginLogicalLeft;
LayoutUnit maxRight = marginLogicalRight > 0 ? max(floatRightWidth, marginLogicalRight) : floatRightWidth + marginLogicalRight;
w = childMaxPreferredLogicalWidth + maxLeft + maxRight;
w = max(w, floatLeftWidth + floatRightWidth);
}
else
m_maxPreferredLogicalWidth = max(floatLeftWidth + floatRightWidth, m_maxPreferredLogicalWidth);
floatLeftWidth = floatRightWidth = 0;
}
if (child->isFloating()) {
if (styleToUse->floating() == LeftFloat)
floatLeftWidth += w;
else
floatRightWidth += w;
} else
m_maxPreferredLogicalWidth = max(w, m_maxPreferredLogicalWidth);
child = child->nextSibling();
}
m_minPreferredLogicalWidth = max<LayoutUnit>(0, m_minPreferredLogicalWidth);
m_maxPreferredLogicalWidth = max<LayoutUnit>(0, m_maxPreferredLogicalWidth);
m_maxPreferredLogicalWidth = max(floatLeftWidth + floatRightWidth, m_maxPreferredLogicalWidth);
}
bool RenderBlock::hasLineIfEmpty() const
{
if (!node())
return false;
if (node()->rendererIsEditable() && node()->rootEditableElement() == node())
return true;
if (node()->isShadowRoot() && (node()->shadowHost()->hasTagName(inputTag)))
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()->usesFirstLineRules()) {
RenderStyle* s = style(firstLine);
if (s != style())
return s->computedLineHeight(view());
}
if (m_lineHeight == -1)
m_lineHeight = style()->computedLineHeight(view());
return m_lineHeight;
}
LayoutUnit 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());
LayoutUnit baselinePos = ignoreBaseline ? static_cast<LayoutUnit>(-1) : lastLineBoxBaseline();
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 FontMetrics& fontMetrics = style(firstLine)->fontMetrics();
return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
}
LayoutUnit RenderBlock::firstLineBoxBaseline() const
{
if (!isBlockFlow() || (isWritingModeRoot() && !isRubyRun()))
return -1;
if (childrenInline()) {
if (firstLineBox())
return firstLineBox()->logicalTop() + style(true)->fontMetrics().ascent(firstRootBox()->baselineType());
else
return -1;
}
else {
for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
if (!curr->isFloatingOrOutOfFlowPositioned()) {
LayoutUnit result = curr->firstLineBoxBaseline();
if (result != -1)
return curr->logicalTop() + result; }
}
}
return -1;
}
LayoutUnit RenderBlock::lastLineBoxBaseline() const
{
if (!isBlockFlow() || (isWritingModeRoot() && !isRubyRun()))
return -1;
LineDirectionMode lineDirection = isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
if (childrenInline()) {
if (!firstLineBox() && hasLineIfEmpty()) {
const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
return fontMetrics.ascent()
+ (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
+ (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
}
if (lastLineBox())
return lastLineBox()->logicalTop() + style(lastLineBox() == firstLineBox())->fontMetrics().ascent(lastRootBox()->baselineType());
return -1;
} else {
bool haveNormalFlowChild = false;
for (RenderBox* curr = lastChildBox(); curr; curr = curr->previousSiblingBox()) {
if (!curr->isFloatingOrOutOfFlowPositioned()) {
haveNormalFlowChild = true;
LayoutUnit result = curr->lastLineBoxBaseline();
if (result != -1)
return curr->logicalTop() + result; }
}
if (!haveNormalFlowChild && hasLineIfEmpty()) {
const FontMetrics& fontMetrics = firstLineStyle()->fontMetrics();
return fontMetrics.ascent()
+ (lineHeight(true, lineDirection, PositionOfInteriorLineBoxes) - fontMetrics.height()) / 2
+ (lineDirection == HorizontalLine ? borderTop() + paddingTop() : borderRight() + paddingRight());
}
}
return -1;
}
bool RenderBlock::containsNonZeroBidiLevel() const
{
for (RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox()) {
for (InlineBox* box = root->firstLeafChild(); box; box = box->nextLeafChild()) {
if (box->bidiLevel())
return true;
}
}
return false;
}
RenderBlock* RenderBlock::firstLineBlock() const
{
RenderBlock* firstLineBlock = const_cast<RenderBlock*>(this);
bool hasPseudo = false;
while (true) {
hasPseudo = firstLineBlock->style()->hasPseudoStyle(FIRST_LINE);
if (hasPseudo)
break;
RenderObject* parentBlock = firstLineBlock->parent();
if (firstLineBlock->isReplaced() || firstLineBlock->isFloating() ||
!parentBlock || parentBlock->firstChild() != firstLineBlock || !parentBlock->isBlockFlow())
break;
ASSERT(parentBlock->isRenderBlock());
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)
{
CharCategory charCategory = category(c);
return charCategory == Punctuation_Open
|| charCategory == Punctuation_Close
|| charCategory == Punctuation_InitialQuote
|| charCategory == Punctuation_FinalQuote
|| charCategory == Punctuation_Other;
}
static inline bool shouldSkipForFirstLetter(UChar c)
{
return isSpaceOrNewline(c) || c == noBreakSpace || isPunctuationForFirstLetter(c);
}
static inline RenderObject* findFirstLetterBlock(RenderBlock* start)
{
RenderObject* firstLetterBlock = start;
while (true) {
bool canHaveFirstLetterRenderer = firstLetterBlock->style()->hasPseudoStyle(FIRST_LETTER)
&& canHaveGeneratedChildren(firstLetterBlock);
if (canHaveFirstLetterRenderer)
return firstLetterBlock;
RenderObject* parentBlock = firstLetterBlock->parent();
if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock ||
!parentBlock->isBlockFlow())
return 0;
firstLetterBlock = parentBlock;
}
return 0;
}
void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderObject* currentChild)
{
RenderObject* firstLetter = currentChild->parent();
RenderObject* firstLetterContainer = firstLetter->parent();
RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
ASSERT(firstLetter->isFloating() || firstLetter->isInline());
if (Node::diff(firstLetter->style(), pseudoStyle, document()) == Node::Detach) {
RenderObject* newFirstLetter;
if (pseudoStyle->display() == INLINE)
newFirstLetter = new (renderArena()) RenderInline(document());
else
newFirstLetter = new (renderArena()) RenderBlock(document());
newFirstLetter->setStyle(pseudoStyle);
LayoutStateDisabler layoutStateDisabler(view());
while (RenderObject* child = firstLetter->firstChild()) {
if (child->isText())
toRenderText(child)->removeAndDestroyTextBoxes();
firstLetter->removeChild(child);
newFirstLetter->addChild(child, 0);
}
RenderTextFragment* remainingText = 0;
RenderObject* nextSibling = firstLetter->nextSibling();
RenderObject* remainingTextObject = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText();
if (remainingTextObject && remainingTextObject->isText() && toRenderText(remainingTextObject)->isTextFragment())
remainingText = toRenderTextFragment(remainingTextObject);
if (remainingText) {
ASSERT(remainingText->isAnonymous() || remainingText->node()->renderer() == remainingText);
remainingText->setFirstLetter(newFirstLetter);
toRenderBoxModelObject(newFirstLetter)->setFirstLetterRemainingText(remainingText);
}
firstLetterContainer->virtualChildren()->removeChildNode(firstLetterContainer, firstLetter);
firstLetter->destroy();
firstLetter = newFirstLetter;
firstLetterContainer->addChild(firstLetter, nextSibling);
} else
firstLetter->setStyle(pseudoStyle);
for (RenderObject* genChild = firstLetter->firstChild(); genChild; genChild = genChild->nextSibling()) {
if (genChild->isText())
genChild->setStyle(pseudoStyle);
}
}
void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, RenderObject* currentChild)
{
RenderObject* firstLetterContainer = currentChild->parent();
RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
RenderObject* firstLetter = 0;
if (pseudoStyle->display() == INLINE)
firstLetter = new (renderArena()) RenderInline(document());
else
firstLetter = new (renderArena()) RenderBlock(document());
firstLetter->setStyle(pseudoStyle);
firstLetterContainer->addChild(firstLetter, currentChild);
RenderText* textObj = toRenderText(currentChild);
RefPtr<StringImpl> oldText = textObj->originalText();
ASSERT(oldText);
if (oldText && oldText->length() > 0) {
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 =
new (renderArena()) RenderTextFragment(textObj->node() ? textObj->node() : textObj->document(), oldText.get(), length, oldText->length() - length);
remainingText->setStyle(textObj->style());
if (remainingText->node())
remainingText->node()->setRenderer(remainingText);
firstLetterContainer->addChild(remainingText, textObj);
firstLetterContainer->removeChild(textObj);
remainingText->setFirstLetter(firstLetter);
toRenderBoxModelObject(firstLetter)->setFirstLetterRemainingText(remainingText);
RenderTextFragment* letter =
new (renderArena()) RenderTextFragment(remainingText->node() ? remainingText->node() : remainingText->document(), oldText.get(), 0, length);
letter->setStyle(pseudoStyle);
firstLetter->addChild(letter);
textObj->destroy();
}
}
void RenderBlock::updateFirstLetter()
{
if (!document()->usesFirstLetterRules())
return;
if (style()->styleType() == FIRST_LETTER)
return;
RenderObject* firstLetterBlock = findFirstLetterBlock(this);
if (!firstLetterBlock)
return;
RenderObject* currChild = firstLetterBlock->firstChild();
while (currChild) {
if (currChild->isText())
break;
if (currChild->isListMarker())
currChild = currChild->nextSibling();
else if (currChild->isFloatingOrOutOfFlowPositioned()) {
if (currChild->style()->styleType() == FIRST_LETTER) {
currChild = currChild->firstChild();
break;
}
currChild = currChild->nextSibling();
} else if (currChild->isReplaced() || currChild->isRenderButton() || currChild->isMenuList())
break;
else if (currChild->style()->hasPseudoStyle(FIRST_LETTER) && canHaveGeneratedChildren(currChild)) {
firstLetterBlock = currChild;
currChild = currChild->firstChild();
} else
currChild = currChild->firstChild();
}
if (!currChild)
return;
if (currChild->parent()->style()->styleType() == FIRST_LETTER) {
updateFirstLetterStyle(firstLetterBlock, currChild);
return;
}
if (!currChild->isText() || currChild->isBR())
return;
LayoutStateDisabler layoutStateDisabler(view());
createFirstLetterRenderer(firstLetterBlock, currChild);
}
static bool shouldCheckLines(RenderObject* obj)
{
return !obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn()
&& obj->isBlockFlow() && obj->style()->height().isAuto()
&& (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
}
static RootInlineBox* getLineAtIndex(RenderBlock* block, int i, int& count)
{
if (block->style()->visibility() == VISIBLE) {
if (block->childrenInline()) {
for (RootInlineBox* box = block->firstRootBox(); box; box = box->nextRootBox()) {
if (count++ == i)
return box;
}
}
else {
for (RenderObject* obj = block->firstChild(); obj; obj = obj->nextSibling()) {
if (shouldCheckLines(obj)) {
RootInlineBox *box = getLineAtIndex(toRenderBlock(obj), i, count);
if (box)
return box;
}
}
}
}
return 0;
}
static int getHeightForLineCount(RenderBlock* block, int l, bool includeBottom, int& count)
{
if (block->style()->visibility() == VISIBLE) {
if (block->childrenInline()) {
for (RootInlineBox* box = block->firstRootBox(); box; box = box->nextRootBox()) {
if (++count == l)
return box->lineBottom() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : ZERO_LAYOUT_UNIT);
}
}
else {
RenderBox* normalFlowChildWithoutLines = 0;
for (RenderBox* obj = block->firstChildBox(); obj; obj = obj->nextSiblingBox()) {
if (shouldCheckLines(obj)) {
int result = getHeightForLineCount(toRenderBlock(obj), l, false, count);
if (result != -1)
return result + obj->y() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : ZERO_LAYOUT_UNIT);
} else if (!obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn())
normalFlowChildWithoutLines = obj;
}
if (normalFlowChildWithoutLines && l == 0)
return normalFlowChildWithoutLines->y() + normalFlowChildWithoutLines->height();
}
}
return -1;
}
RootInlineBox* RenderBlock::lineAtIndex(int i)
{
int count = 0;
return getLineAtIndex(this, i, count);
}
int RenderBlock::lineCount()
{
int count = 0;
if (style()->visibility() == VISIBLE) {
if (childrenInline())
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
count++;
else
for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling())
if (shouldCheckLines(obj))
count += toRenderBlock(obj)->lineCount();
}
return count;
}
int RenderBlock::heightForLineCount(int l)
{
int count = 0;
return getHeightForLineCount(this, l, true, count);
}
void RenderBlock::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
{
if (style()->visibility() == VISIBLE) {
if (childrenInline()) {
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) {
if (box->firstChild())
left = min(left, x + static_cast<LayoutUnit>(box->firstChild()->x()));
if (box->lastChild())
right = max(right, x + static_cast<LayoutUnit>(ceilf(box->lastChild()->logicalRight())));
}
}
else {
for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
if (!obj->isFloatingOrOutOfFlowPositioned()) {
if (obj->isBlockFlow() && !obj->hasOverflowClip())
toRenderBlock(obj)->adjustForBorderFit(x + obj->x(), left, right);
else if (obj->style()->visibility() == VISIBLE) {
left = min(left, x + obj->x());
right = max(right, x + obj->x() + obj->width());
}
}
}
}
if (m_floatingObjects) {
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
FloatingObject* r = *it;
if (r->shouldPaint()) {
LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->m_renderer->x();
LayoutUnit floatRight = floatLeft + r->m_renderer->width();
left = min(left, floatLeft);
right = max(right, floatRight);
}
}
}
}
}
void RenderBlock::borderFitAdjust(LayoutRect& rect) const
{
if (style()->borderFit() == BorderFitBorder)
return;
LayoutUnit left = MAX_LAYOUT_UNIT;
LayoutUnit right = MIN_LAYOUT_UNIT;
LayoutUnit oldWidth = rect.width();
adjustForBorderFit(0, left, right);
if (left != MAX_LAYOUT_UNIT) {
left = min(left, oldWidth - (borderRight() + paddingRight()));
left -= (borderLeft() + paddingLeft());
if (left > 0) {
rect.move(left, 0);
rect.expand(-left, 0);
}
}
if (right != MIN_LAYOUT_UNIT) {
right = max(right, borderLeft() + paddingLeft());
right += (borderRight() + paddingRight());
if (right < oldWidth)
rect.expand(-(oldWidth - right), 0);
}
}
void RenderBlock::clearTruncation()
{
if (style()->visibility() == VISIBLE) {
if (childrenInline() && hasMarkupTruncation()) {
setHasMarkupTruncation(false);
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
box->clearTruncation();
} else {
for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling()) {
if (shouldCheckLines(obj))
toRenderBlock(obj)->clearTruncation();
}
}
}
}
void RenderBlock::setMaxMarginBeforeValues(LayoutUnit pos, LayoutUnit neg)
{
if (!m_rareData) {
if (pos == RenderBlockRareData::positiveMarginBeforeDefault(this) && neg == RenderBlockRareData::negativeMarginBeforeDefault(this))
return;
m_rareData = adoptPtr(new RenderBlockRareData(this));
}
m_rareData->m_margins.setPositiveMarginBefore(pos);
m_rareData->m_margins.setNegativeMarginBefore(neg);
}
void RenderBlock::setMaxMarginAfterValues(LayoutUnit pos, LayoutUnit neg)
{
if (!m_rareData) {
if (pos == RenderBlockRareData::positiveMarginAfterDefault(this) && neg == RenderBlockRareData::negativeMarginAfterDefault(this))
return;
m_rareData = adoptPtr(new RenderBlockRareData(this));
}
m_rareData->m_margins.setPositiveMarginAfter(pos);
m_rareData->m_margins.setNegativeMarginAfter(neg);
}
void RenderBlock::setPaginationStrut(LayoutUnit strut)
{
if (!m_rareData) {
if (!strut)
return;
m_rareData = adoptPtr(new RenderBlockRareData(this));
}
m_rareData->m_paginationStrut = strut;
}
void RenderBlock::setPageLogicalOffset(LayoutUnit logicalOffset)
{
if (!m_rareData) {
if (!logicalOffset)
return;
m_rareData = adoptPtr(new RenderBlockRareData(this));
}
m_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
{
if (isAnonymousBlockContinuation()) {
FloatRect localRect(0, -collapsedMarginBefore(),
width(), height() + collapsedMarginBefore() + collapsedMarginAfter());
quads.append(localToAbsoluteQuad(localRect, false, wasFixed));
continuation()->absoluteQuads(quads, wasFixed);
} else
quads.append(RenderBox::localToAbsoluteQuad(FloatRect(0, 0, width(), height()), false, wasFixed));
}
LayoutRect RenderBlock::rectWithOutlineForRepaint(RenderBoxModelObject* repaintContainer, LayoutUnit outlineWidth) const
{
LayoutRect r(RenderBox::rectWithOutlineForRepaint(repaintContainer, outlineWidth));
if (isAnonymousBlockContinuation())
r.inflateY(collapsedMarginBefore()); return r;
}
RenderObject* RenderBlock::hoverAncestor() const
{
return isAnonymousBlockContinuation() ? continuation() : RenderBox::hoverAncestor();
}
void RenderBlock::updateDragState(bool dragOn)
{
RenderBox::updateDragState(dragOn);
if (continuation())
continuation()->updateDragState(dragOn);
}
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;
Node* n = node();
if (isAnonymousBlockContinuation())
n = continuation()->node();
if (n) {
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);
RenderStyle* currentStyle = firstLineStyle();
LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
enum CaretAlignment { alignLeft, alignRight, alignCenter };
CaretAlignment alignment = alignLeft;
switch (currentStyle->textAlign()) {
case TAAUTO:
case JUSTIFY:
if (!currentStyle->isLeftToRightDirection())
alignment = alignRight;
break;
case LEFT:
case WEBKIT_LEFT:
break;
case CENTER:
case WEBKIT_CENTER:
alignment = alignCenter;
break;
case RIGHT:
case WEBKIT_RIGHT:
alignment = alignRight;
break;
case TASTART:
if (!currentStyle->isLeftToRightDirection())
alignment = alignRight;
break;
case TAEND:
if (currentStyle->isLeftToRightDirection())
alignment = alignRight;
break;
}
LayoutUnit x = borderLeft() + paddingLeft();
LayoutUnit w = width();
switch (alignment) {
case alignLeft:
if (currentStyle->isLeftToRightDirection())
x += textIndentOffset();
break;
case alignCenter:
x = (x + w - (borderRight() + paddingRight())) / 2;
if (currentStyle->isLeftToRightDirection())
x += textIndentOffset() / 2;
else
x -= textIndentOffset() / 2;
break;
case alignRight:
x = w - (borderRight() + paddingRight()) - caretWidth;
if (!currentStyle->isLeftToRightDirection())
x -= textIndentOffset();
break;
}
x = min(x, w - borderRight() - paddingRight() - caretWidth);
if (extraWidthToEndOfLine) {
if (isRenderBlock()) {
*extraWidthToEndOfLine = w - (x + caretWidth);
} else {
LayoutUnit myRight = x + caretWidth;
FloatPoint absRightPoint = localToAbsolute(FloatPoint(myRight, 0));
LayoutUnit containerRight = containingBlock()->x() + containingBlockLogicalWidthForContent();
FloatPoint absContainerPoint = localToAbsolute(FloatPoint(containerRight, 0));
*extraWidthToEndOfLine = absContainerPoint.x() - absRightPoint.x();
}
}
LayoutUnit y = paddingTop() + borderTop();
return LayoutRect(x, y, caretWidth, height);
}
void RenderBlock::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& additionalOffset)
{
if (inlineElementContinuation()) {
bool nextInlineHasLineBox = inlineElementContinuation()->firstLineBox();
bool prevInlineHasLineBox = toRenderInline(inlineElementContinuation()->node()->renderer())->firstLineBox();
float topMargin = prevInlineHasLineBox ? collapsedMarginBefore() : static_cast<LayoutUnit>(0);
float bottomMargin = nextInlineHasLineBox ? collapsedMarginAfter() : static_cast<LayoutUnit>(0);
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()) {
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
LayoutUnit top = max<LayoutUnit>(curr->lineTop(), curr->top());
LayoutUnit bottom = min<LayoutUnit>(curr->lineBottom(), curr->top() + curr->height());
LayoutRect rect(additionalOffset.x() + curr->x(), additionalOffset.y() + top, curr->width(), bottom - top);
if (!rect.isEmpty())
rects.append(pixelSnappedIntRect(rect));
}
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->localToAbsolute();
else
pos = FloatPoint(additionalOffset.x() + box->x(), additionalOffset.y() + box->y());
box->addFocusRingRects(rects, flooredLayoutPoint(pos));
}
}
}
if (inlineElementContinuation())
inlineElementContinuation()->addFocusRingRects(rects, flooredLayoutPoint(additionalOffset + inlineElementContinuation()->containingBlock()->location() - location()));
}
RenderBox* RenderBlock::createAnonymousBoxWithSameTypeAs(const RenderObject* parent) const
{
if (isAnonymousColumnsBlock())
return createAnonymousColumnsWithParentRenderer(parent);
if (isAnonymousColumnSpanBlock())
return createAnonymousColumnSpanWithParentRenderer(parent);
return createAnonymousWithParentRendererAndDisplay(parent, style()->display());
}
bool RenderBlock::hasNextPage(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
{
ASSERT(view()->layoutState() && view()->layoutState()->isPaginated());
if (!inRenderFlowThread())
return true;
LayoutUnit pageOffset = offsetFromLogicalTopOfFirstPage() + logicalOffset;
RenderRegion* region = enclosingRenderFlowThread()->renderRegionForLine(pageOffset, this);
if (!region)
return false;
if (region->isLastRegion())
return region->style()->regionOverflow() == BreakRegionOverflow
|| (pageBoundaryRule == IncludePageBoundary && pageOffset == region->offsetFromLogicalTopOfFirstPage());
return true;
}
LayoutUnit RenderBlock::nextPageLogicalTop(LayoutUnit logicalOffset, PageBoundaryRule pageBoundaryRule) const
{
LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
if (!pageLogicalHeight)
return logicalOffset;
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset);
if (pageBoundaryRule == ExcludePageBoundary)
return logicalOffset + (remainingLogicalHeight ? remainingLogicalHeight : pageLogicalHeight);
return logicalOffset + remainingLogicalHeight;
}
static bool inNormalFlow(RenderBox* child)
{
RenderBlock* curr = child->containingBlock();
RenderView* renderView = child->view();
while (curr && curr != renderView) {
if (curr->hasColumns() || curr->isRenderFlowThread())
return true;
if (curr->isFloatingOrOutOfFlowPositioned())
return false;
curr = curr->containingBlock();
}
return true;
}
ColumnInfo::PaginationUnit RenderBlock::paginationUnit() const
{
return ColumnInfo::Column;
}
LayoutUnit RenderBlock::applyBeforeBreak(RenderBox* child, LayoutUnit logicalOffset)
{
bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; bool checkRegionBreaks = inRenderFlowThread();
bool checkBeforeAlways = (checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS)
|| (checkRegionBreaks && child->style()->regionBreakBefore() == PBALWAYS);
if (checkBeforeAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
if (checkColumnBreaks)
view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
}
return logicalOffset;
}
LayoutUnit RenderBlock::applyAfterBreak(RenderBox* child, LayoutUnit logicalOffset, MarginInfo& marginInfo)
{
bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight; bool checkRegionBreaks = inRenderFlowThread();
bool checkAfterAlways = (checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS) || (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS)
|| (checkRegionBreaks && child->style()->regionBreakAfter() == PBALWAYS);
if (checkAfterAlways && inNormalFlow(child) && hasNextPage(logicalOffset, IncludePageBoundary)) {
marginInfo.setMarginAfterQuirk(true); if (checkColumnBreaks)
view()->layoutState()->addForcedColumnBreak(child, logicalOffset);
return nextPageLogicalTop(logicalOffset, IncludePageBoundary);
}
return logicalOffset;
}
LayoutUnit RenderBlock::pageLogicalTopForOffset(LayoutUnit offset) const
{
RenderView* renderView = view();
LayoutUnit firstPageLogicalTop = isHorizontalWritingMode() ? renderView->layoutState()->m_pageOffset.height() : renderView->layoutState()->m_pageOffset.width();
LayoutUnit blockLogicalTop = isHorizontalWritingMode() ? renderView->layoutState()->m_layoutOffset.height() : renderView->layoutState()->m_layoutOffset.width();
LayoutUnit cumulativeOffset = offset + blockLogicalTop;
if (!inRenderFlowThread()) {
LayoutUnit pageLogicalHeight = renderView->layoutState()->pageLogicalHeight();
if (!pageLogicalHeight)
return 0;
return cumulativeOffset - roundToInt(cumulativeOffset - firstPageLogicalTop) % roundToInt(pageLogicalHeight);
}
return enclosingRenderFlowThread()->regionLogicalTopForLine(cumulativeOffset);
}
LayoutUnit RenderBlock::pageLogicalHeightForOffset(LayoutUnit offset) const
{
RenderView* renderView = view();
if (!inRenderFlowThread())
return renderView->layoutState()->m_pageLogicalHeight;
return enclosingRenderFlowThread()->regionLogicalHeightForLine(offset + offsetFromLogicalTopOfFirstPage());
}
LayoutUnit RenderBlock::pageRemainingLogicalHeightForOffset(LayoutUnit offset, PageBoundaryRule pageBoundaryRule) const
{
RenderView* renderView = view();
offset += offsetFromLogicalTopOfFirstPage();
if (!inRenderFlowThread()) {
LayoutUnit pageLogicalHeight = renderView->layoutState()->m_pageLogicalHeight;
LayoutUnit remainingHeight = pageLogicalHeight - layoutMod(offset, pageLogicalHeight);
if (pageBoundaryRule == IncludePageBoundary) {
remainingHeight = layoutMod(remainingHeight, pageLogicalHeight);
}
return remainingHeight;
}
return enclosingRenderFlowThread()->regionRemainingLogicalHeightForLine(offset, pageBoundaryRule);
}
LayoutUnit RenderBlock::adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins)
{
bool checkColumnBreaks = view()->layoutState()->isPaginatingColumns();
bool checkPageBreaks = !checkColumnBreaks && view()->layoutState()->m_pageLogicalHeight;
bool checkRegionBreaks = inRenderFlowThread();
bool isUnsplittable = child->isUnsplittableForPagination() || (checkColumnBreaks && child->style()->columnBreakInside() == PBAVOID)
|| (checkPageBreaks && child->style()->pageBreakInside() == PBAVOID)
|| (checkRegionBreaks && child->style()->regionBreakInside() == PBAVOID);
if (!isUnsplittable)
return logicalOffset;
LayoutUnit childLogicalHeight = logicalHeightForChild(child) + (includeMargins ? marginBeforeForChild(child) + marginAfterForChild(child) : ZERO_LAYOUT_UNIT);
LayoutState* layoutState = view()->layoutState();
if (layoutState->m_columnInfo)
layoutState->m_columnInfo->updateMinimumColumnHeight(childLogicalHeight);
LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
bool hasUniformPageLogicalHeight = !inRenderFlowThread() || enclosingRenderFlowThread()->regionsHaveUniformLogicalHeight();
if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
|| !hasNextPage(logicalOffset))
return logicalOffset;
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
if (remainingLogicalHeight < childLogicalHeight) {
if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, childLogicalHeight))
return logicalOffset;
return logicalOffset + remainingLogicalHeight;
}
return logicalOffset;
}
bool RenderBlock::pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const
{
bool checkRegion = false;
for (LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment); pageLogicalHeight;
pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset + adjustment)) {
if (minimumLogicalHeight <= pageLogicalHeight)
return true;
if (!hasNextPage(logicalOffset + adjustment))
return false;
adjustment += pageLogicalHeight;
checkRegion = true;
}
return !checkRegion;
}
void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta)
{
LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
LayoutUnit logicalOffset = min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
LayoutUnit lineHeight = max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY()) - logicalOffset;
RenderView* renderView = view();
LayoutState* layoutState = renderView->layoutState();
if (layoutState->m_columnInfo)
layoutState->m_columnInfo->updateMinimumColumnHeight(lineHeight);
logicalOffset += delta;
lineBox->setPaginationStrut(0);
lineBox->setIsFirstAfterPageBreak(false);
LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
bool hasUniformPageLogicalHeight = !inRenderFlowThread() || enclosingRenderFlowThread()->regionsHaveUniformLogicalHeight();
if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight)
|| !hasNextPage(logicalOffset))
return;
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
if (remainingLogicalHeight < lineHeight) {
if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, lineHeight))
return;
if (lineHeight > pageLogicalHeight) {
remainingLogicalHeight -= min(lineHeight - pageLogicalHeight, max<LayoutUnit>(0, logicalVisualOverflow.y() - lineBox->lineTopWithLeading()));
}
LayoutUnit totalLogicalHeight = lineHeight + max<LayoutUnit>(0, logicalOffset);
LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
if (lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset && !isOutOfFlowPositioned() && !isTableCell())
setPaginationStrut(remainingLogicalHeight + max(ZERO_LAYOUT_UNIT, logicalOffset));
else {
delta += remainingLogicalHeight;
lineBox->setPaginationStrut(remainingLogicalHeight);
lineBox->setIsFirstAfterPageBreak(true);
}
} else if (remainingLogicalHeight == pageLogicalHeight && lineBox != firstRootBox())
lineBox->setIsFirstAfterPageBreak(true);
}
LayoutUnit RenderBlock::adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock)
{
RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
if (estimateWithoutPagination != logicalTopAfterClear) {
setLogicalHeight(logicalTopAfterClear);
setLogicalTopForChild(child, logicalTopAfterClear, ApplyLayoutDelta);
if (child->shrinkToAvoidFloats()) {
child->setChildNeedsLayout(true, MarkOnlyThis);
}
if (childRenderBlock) {
if (!child->avoidsFloats() && childRenderBlock->containsFloats())
childRenderBlock->markAllDescendantsWithFloatsForLayout();
if (!child->needsLayout())
child->markForPaginationRelayoutIfNeeded();
}
child->layoutIfNeeded();
}
LayoutUnit oldTop = logicalTopAfterClear;
LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
LayoutUnit paginationStrut = 0;
LayoutUnit unsplittableAdjustmentDelta = logicalTopAfterUnsplittableAdjustment - logicalTopBeforeUnsplittableAdjustment;
if (unsplittableAdjustmentDelta)
paginationStrut = unsplittableAdjustmentDelta;
else if (childRenderBlock && childRenderBlock->paginationStrut())
paginationStrut = childRenderBlock->paginationStrut();
if (paginationStrut) {
if (atBeforeSideOfBlock && oldTop == result && !isOutOfFlowPositioned() && !isTableCell()) {
setPaginationStrut(result + paginationStrut);
if (childRenderBlock)
childRenderBlock->setPaginationStrut(0);
} else
result += paginationStrut;
}
setLogicalHeight(logicalHeight() + (result - oldTop));
return result;
}
bool RenderBlock::lineWidthForPaginatedLineChanged(RootInlineBox* rootBox, LayoutUnit lineDelta) const
{
if (!inRenderFlowThread())
return false;
return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(rootBox->lineTopWithLeading() + lineDelta);
}
LayoutUnit RenderBlock::offsetFromLogicalTopOfFirstPage() const
{
LayoutState* layoutState = view()->layoutState();
if (!layoutState || !layoutState->isPaginated())
return 0;
LayoutSize offsetDelta = layoutState->m_layoutOffset - layoutState->m_pageOffset;
return isHorizontalWritingMode() ? offsetDelta.height() : offsetDelta.width();
}
RenderRegion* RenderBlock::regionAtBlockOffset(LayoutUnit blockOffset) const
{
if (!inRenderFlowThread())
return 0;
RenderFlowThread* flowThread = enclosingRenderFlowThread();
if (!flowThread || !flowThread->hasValidRegionInfo())
return 0;
return flowThread->renderRegionForLine(offsetFromLogicalTopOfFirstPage() + blockOffset, true);
}
void RenderBlock::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
{
if (inRenderFlowThread()) {
inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
}
child->layer()->setStaticInlinePosition(inlinePosition);
}
bool RenderBlock::logicalWidthChangedInRegions() const
{
if (!inRenderFlowThread())
return false;
RenderFlowThread* flowThread = enclosingRenderFlowThread();
if (!flowThread || !flowThread->hasValidRegionInfo())
return 0;
return flowThread->logicalWidthChangedInRegions(this, offsetFromLogicalTopOfFirstPage());
}
RenderRegion* RenderBlock::clampToStartAndEndRegions(RenderRegion* region) const
{
ASSERT(region && inRenderFlowThread());
RenderRegion* startRegion;
RenderRegion* endRegion;
enclosingRenderFlowThread()->getRegionRangeForBox(this, startRegion, endRegion);
if (startRegion && region->offsetFromLogicalTopOfFirstPage() < startRegion->offsetFromLogicalTopOfFirstPage())
return startRegion;
if (endRegion && region->offsetFromLogicalTopOfFirstPage() > endRegion->offsetFromLogicalTopOfFirstPage())
return endRegion;
return region;
}
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);
}
LayoutUnit RenderBlock::marginBeforeForChild(const RenderBoxModelObject* child) const
{
switch (style()->writingMode()) {
case TopToBottomWritingMode:
return child->marginTop();
case BottomToTopWritingMode:
return child->marginBottom();
case LeftToRightWritingMode:
return child->marginLeft();
case RightToLeftWritingMode:
return child->marginRight();
}
ASSERT_NOT_REACHED();
return child->marginTop();
}
LayoutUnit RenderBlock::marginAfterForChild(const RenderBoxModelObject* child) const
{
switch (style()->writingMode()) {
case TopToBottomWritingMode:
return child->marginBottom();
case BottomToTopWritingMode:
return child->marginTop();
case LeftToRightWritingMode:
return child->marginRight();
case RightToLeftWritingMode:
return child->marginLeft();
}
ASSERT_NOT_REACHED();
return child->marginBottom();
}
LayoutUnit RenderBlock::marginStartForChild(const RenderBoxModelObject* child) const
{
if (isHorizontalWritingMode())
return style()->isLeftToRightDirection() ? child->marginLeft() : child->marginRight();
return style()->isLeftToRightDirection() ? child->marginTop() : child->marginBottom();
}
LayoutUnit RenderBlock::marginEndForChild(const RenderBoxModelObject* child) const
{
if (isHorizontalWritingMode())
return style()->isLeftToRightDirection() ? child->marginRight() : child->marginLeft();
return style()->isLeftToRightDirection() ? child->marginBottom() : child->marginTop();
}
void RenderBlock::setMarginStartForChild(RenderBox* child, LayoutUnit margin) const
{
if (isHorizontalWritingMode()) {
if (style()->isLeftToRightDirection())
child->setMarginLeft(margin);
else
child->setMarginRight(margin);
} else {
if (style()->isLeftToRightDirection())
child->setMarginTop(margin);
else
child->setMarginBottom(margin);
}
}
void RenderBlock::setMarginEndForChild(RenderBox* child, LayoutUnit margin) const
{
if (isHorizontalWritingMode()) {
if (style()->isLeftToRightDirection())
child->setMarginRight(margin);
else
child->setMarginLeft(margin);
} else {
if (style()->isLeftToRightDirection())
child->setMarginBottom(margin);
else
child->setMarginTop(margin);
}
}
void RenderBlock::setMarginBeforeForChild(RenderBox* child, LayoutUnit margin) const
{
switch (style()->writingMode()) {
case TopToBottomWritingMode:
child->setMarginTop(margin);
break;
case BottomToTopWritingMode:
child->setMarginBottom(margin);
break;
case LeftToRightWritingMode:
child->setMarginLeft(margin);
break;
case RightToLeftWritingMode:
child->setMarginRight(margin);
break;
}
}
void RenderBlock::setMarginAfterForChild(RenderBox* child, LayoutUnit margin) const
{
switch (style()->writingMode()) {
case TopToBottomWritingMode:
child->setMarginBottom(margin);
break;
case BottomToTopWritingMode:
child->setMarginTop(margin);
break;
case LeftToRightWritingMode:
child->setMarginRight(margin);
break;
case RightToLeftWritingMode:
child->setMarginLeft(margin);
break;
}
}
RenderBlock::MarginValues RenderBlock::marginValuesForChild(RenderBox* child) const
{
LayoutUnit childBeforePositive = 0;
LayoutUnit childBeforeNegative = 0;
LayoutUnit childAfterPositive = 0;
LayoutUnit childAfterNegative = 0;
LayoutUnit beforeMargin = 0;
LayoutUnit afterMargin = 0;
RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
if (!child->isWritingModeRoot()) {
if (childRenderBlock) {
childBeforePositive = childRenderBlock->maxPositiveMarginBefore();
childBeforeNegative = childRenderBlock->maxNegativeMarginBefore();
childAfterPositive = childRenderBlock->maxPositiveMarginAfter();
childAfterNegative = childRenderBlock->maxNegativeMarginAfter();
} else {
beforeMargin = child->marginBefore();
afterMargin = child->marginAfter();
}
} else if (child->isHorizontalWritingMode() == isHorizontalWritingMode()) {
if (childRenderBlock) {
childBeforePositive = childRenderBlock->maxPositiveMarginAfter();
childBeforeNegative = childRenderBlock->maxNegativeMarginAfter();
childAfterPositive = childRenderBlock->maxPositiveMarginBefore();
childAfterNegative = childRenderBlock->maxNegativeMarginBefore();
} else {
beforeMargin = child->marginAfter();
afterMargin = child->marginBefore();
}
} else {
beforeMargin = marginBeforeForChild(child);
afterMargin = marginAfterForChild(child);
}
if (beforeMargin) {
if (beforeMargin > 0)
childBeforePositive = beforeMargin;
else
childBeforeNegative = -beforeMargin;
}
if (afterMargin) {
if (afterMargin > 0)
childAfterPositive = afterMargin;
else
childAfterNegative = -afterMargin;
}
return MarginValues(childBeforePositive, childBeforeNegative, childAfterPositive, childAfterNegative);
}
const char* RenderBlock::renderName() const
{
if (isBody())
return "RenderBody";
if (isFloating())
return "RenderBlock (floating)";
if (isOutOfFlowPositioned())
return "RenderBlock (positioned)";
if (isAnonymousColumnsBlock())
return "RenderBlock (anonymous multi-column)";
if (isAnonymousColumnSpanBlock())
return "RenderBlock (anonymous multi-column span)";
if (isAnonymousBlock())
return "RenderBlock (anonymous)";
else if (isAnonymous())
return "RenderBlock (generated)";
if (isRelPositioned())
return "RenderBlock (relative positioned)";
if (isStickyPositioned())
return "RenderBlock (sticky positioned)";
if (isRunIn())
return "RenderBlock (run-in)";
return "RenderBlock";
}
inline void RenderBlock::FloatingObjects::clear()
{
m_set.clear();
m_placedFloatsTree.clear();
m_leftObjectsCount = 0;
m_rightObjectsCount = 0;
}
inline void RenderBlock::FloatingObjects::increaseObjectsCount(FloatingObject::Type type)
{
if (type == FloatingObject::FloatLeft)
m_leftObjectsCount++;
else
m_rightObjectsCount++;
}
inline void RenderBlock::FloatingObjects::decreaseObjectsCount(FloatingObject::Type type)
{
if (type == FloatingObject::FloatLeft)
m_leftObjectsCount--;
else
m_rightObjectsCount--;
}
inline RenderBlock::FloatingObjectInterval RenderBlock::FloatingObjects::intervalForFloatingObject(FloatingObject* floatingObject)
{
if (m_horizontalWritingMode)
return RenderBlock::FloatingObjectInterval(floatingObject->pixelSnappedY(), floatingObject->pixelSnappedMaxY(), floatingObject);
return RenderBlock::FloatingObjectInterval(floatingObject->pixelSnappedX(), floatingObject->pixelSnappedMaxX(), floatingObject);
}
void RenderBlock::FloatingObjects::addPlacedObject(FloatingObject* floatingObject)
{
ASSERT(!floatingObject->isInPlacedTree());
floatingObject->setIsPlaced(true);
if (m_placedFloatsTree.isInitialized())
m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
#ifndef NDEBUG
floatingObject->setIsInPlacedTree(true);
#endif
}
void RenderBlock::FloatingObjects::removePlacedObject(FloatingObject* floatingObject)
{
ASSERT(floatingObject->isPlaced() && floatingObject->isInPlacedTree());
if (m_placedFloatsTree.isInitialized()) {
bool removed = m_placedFloatsTree.remove(intervalForFloatingObject(floatingObject));
ASSERT_UNUSED(removed, removed);
}
floatingObject->setIsPlaced(false);
#ifndef NDEBUG
floatingObject->setIsInPlacedTree(false);
#endif
}
inline void RenderBlock::FloatingObjects::add(FloatingObject* floatingObject)
{
increaseObjectsCount(floatingObject->type());
m_set.add(floatingObject);
if (floatingObject->isPlaced())
addPlacedObject(floatingObject);
}
inline void RenderBlock::FloatingObjects::remove(FloatingObject* floatingObject)
{
decreaseObjectsCount(floatingObject->type());
m_set.remove(floatingObject);
ASSERT(floatingObject->isPlaced() || !floatingObject->isInPlacedTree());
if (floatingObject->isPlaced())
removePlacedObject(floatingObject);
}
void RenderBlock::FloatingObjects::computePlacedFloatsTree()
{
ASSERT(!m_placedFloatsTree.isInitialized());
if (m_set.isEmpty())
return;
m_placedFloatsTree.initIfNeeded(m_renderer->view()->intervalArena());
FloatingObjectSetIterator it = m_set.begin();
FloatingObjectSetIterator end = m_set.end();
for (; it != end; ++it) {
FloatingObject* floatingObject = *it;
if (floatingObject->isPlaced())
m_placedFloatsTree.add(intervalForFloatingObject(floatingObject));
}
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
{
ASSERT(style);
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, false, 0, 0, expansion, textDirection, directionalOverride);
if (textRunNeedsRenderingContext(font))
run.setRenderingContext(SVGTextRunRenderingContext::create(context));
return run;
}
TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
{
return constructTextRun(context, font, string.characters(), string.length(), style, expansion, flags);
}
RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const RenderObject* parent, EDisplay display)
{
EDisplay newDisplay;
RenderBlock* newBox = 0;
if (display == BOX || display == INLINE_BOX) {
newBox = new (parent->renderArena()) RenderDeprecatedFlexibleBox(parent->document() );
newDisplay = BOX;
} else {
newBox = new (parent->renderArena()) RenderBlock(parent->document() );
newDisplay = BLOCK;
}
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), newDisplay);
newBox->setStyle(newStyle.release());
return newBox;
}
RenderBlock* RenderBlock::createAnonymousColumnsWithParentRenderer(const RenderObject* parent)
{
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
newStyle->inheritColumnPropertiesFrom(parent->style());
RenderBlock* newBox = new (parent->renderArena()) RenderBlock(parent->document() );
newBox->setStyle(newStyle.release());
return newBox;
}
RenderBlock* RenderBlock::createAnonymousColumnSpanWithParentRenderer(const RenderObject* parent)
{
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
newStyle->setColumnSpan(ColumnSpanAll);
RenderBlock* newBox = new (parent->renderArena()) RenderBlock(parent->document() );
newBox->setStyle(newStyle.release());
return newBox;
}
#ifndef NDEBUG
void RenderBlock::showLineTreeAndMark(const InlineBox* markedBox1, const char* markedLabel1, const InlineBox* markedBox2, const char* markedLabel2, const RenderObject* obj) const
{
showRenderObject();
for (const RootInlineBox* root = firstRootBox(); root; root = root->nextRootBox())
root->showLineTreeAndMark(markedBox1, markedLabel1, markedBox2, markedLabel2, obj, 1);
}
String ValueToString<int>::string(const int value)
{
return String::number(value);
}
String ValueToString<RenderBlock::FloatingObject*>::string(const RenderBlock::FloatingObject* floatingObject)
{
return String::format("%p (%dx%d %dx%d)", floatingObject, floatingObject->pixelSnappedX(), floatingObject->pixelSnappedY(), floatingObject->pixelSnappedMaxX(), floatingObject->pixelSnappedMaxY());
}
#endif
#define ParagraphMinWordCount 6
#define ParagraphMinLineCount 2
#define ParagraphMaxWidth 0.9
inline static bool isVisibleRenderText(RenderObject *renderer)
{
if (!renderer->isText())
return false;
RenderText *renderText = toRenderText(renderer);
IntRect boundingBox = renderText->linesBoundingBox();
return boundingBox.width() != 0 && boundingBox.height() != 0 && !renderText->text()->containsOnlyWhitespace();
}
inline static bool resizeTextPermitted(RenderObject *render) {
RenderObject* renderer = render->parent();
while (renderer) {
if (renderer->node() && renderer->node()->isHTMLElement() && !renderer->node()->isInShadowTree()) {
HTMLElement* element = static_cast<HTMLElement*>(renderer->node());
return !element->hasTagName(inputTag) && !element->hasTagName(textareaTag);
}
renderer = renderer->parent();
}
return true;
}
int RenderBlock::immediateLineCount()
{
int count = 0;
if (style()->visibility() == VISIBLE) {
if (childrenInline())
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox())
count++;
else
for (RenderObject* obj = firstChild(); obj; obj = obj->nextSibling())
if (obj->isListItem())
count += static_cast<RenderBlock*>(obj)->lineCount();
}
return count;
}
static bool includeNonBlocksOrListItems(const RenderObject *render)
{
return !render->isRenderBlock() || render->isListItem();
}
static inline float oneLineTextMultiplier(float specifiedSize)
{
return max((1.0f / log10f(specifiedSize) * 1.7f), 1.0f);
}
static inline float textMultiplier(float specifiedSize)
{
return max((1.0f / log10f(specifiedSize) * 1.95f), 1.0f);
}
void RenderBlock::adjustComputedFontSizes(float size, float visibleWidth)
{
if (visibleWidth >= width())
return;
unsigned lineCount;
if (m_lineCountForTextAutosizing == NOT_SET) {
int count = immediateLineCount();
if (count == 0)
lineCount = NO_LINE;
else if (count == 1)
lineCount = ONE_LINE;
else
lineCount = MULTI_LINE;
} else {
lineCount = m_lineCountForTextAutosizing;
}
ASSERT(lineCount != NOT_SET);
if (lineCount == NO_LINE)
return;
float actualWidth = m_widthForTextAutosizing != -1 ? static_cast<float>(m_widthForTextAutosizing) : static_cast<float>(width());
float scale = visibleWidth / actualWidth;
float minFontSize = roundf(size / scale);
for (RenderObject *descendent = traverseNext(this, includeNonBlocksOrListItems); descendent; descendent = descendent->traverseNext(this, includeNonBlocksOrListItems)) {
if (isVisibleRenderText(descendent) && resizeTextPermitted(descendent)) {
RenderText *text = static_cast<RenderText *>(descendent);
RenderStyle *oldStyle = text->style();
FontDescription fontDescription = oldStyle->fontDescription();
float specifiedSize = fontDescription.specifiedSize();
float scaledSize = roundf(specifiedSize * scale);
if (scaledSize > 0 && scaledSize < minFontSize) {
if (m_lineCountForTextAutosizing == NOT_SET)
m_lineCountForTextAutosizing = lineCount;
if (m_widthForTextAutosizing == -1)
m_widthForTextAutosizing = actualWidth;
float candidateNewSize = 0;
if (lineCount == ONE_LINE)
candidateNewSize = roundf(min(minFontSize, specifiedSize * oneLineTextMultiplier(specifiedSize)));
else
candidateNewSize = roundf(min(minFontSize, specifiedSize * textMultiplier(specifiedSize)));
if (candidateNewSize > specifiedSize && candidateNewSize != fontDescription.computedSize() && text->node() && (!oldStyle || oldStyle->textSizeAdjust().isAuto()))
document()->addAutoSizingNode (text->node(), candidateNewSize);
}
}
}
}
}