#include "config.h"
#include "RenderBlock.h"
#include "Document.h"
#include "Element.h"
#include "FloatQuad.h"
#include "Frame.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "HTMLFormElement.h"
#include "HTMLNames.h"
#include "HitTestResult.h"
#include "InlineTextBox.h"
#include "RenderFlexibleBox.h"
#include "RenderImage.h"
#include "RenderInline.h"
#include "RenderMarquee.h"
#include "RenderReplica.h"
#include "RenderTableCell.h"
#include "RenderTextFragment.h"
#include "RenderTheme.h"
#include "RenderView.h"
#include "SelectionController.h"
#include "Settings.h"
#include "TransformState.h"
#include <wtf/StdLibExtras.h>
using namespace std;
using namespace WTF;
using namespace Unicode;
namespace WebCore {
static const int verticalLineClickFudgeFactor = 3;
using namespace HTMLNames;
struct ColumnInfo : public Noncopyable {
ColumnInfo()
: m_desiredColumnWidth(0)
, m_desiredColumnCount(1)
{ }
int m_desiredColumnWidth;
unsigned m_desiredColumnCount;
Vector<IntRect> m_columnRects;
};
typedef WTF::HashMap<const RenderBox*, ColumnInfo*> ColumnInfoMap;
static ColumnInfoMap* gColumnInfoMap = 0;
typedef WTF::HashMap<const RenderBlock*, HashSet<RenderBox*>*> PercentHeightDescendantsMap;
static PercentHeightDescendantsMap* gPercentHeightDescendantsMap = 0;
typedef WTF::HashMap<const RenderBox*, HashSet<RenderBlock*>*> PercentHeightContainerMap;
static PercentHeightContainerMap* gPercentHeightContainerMap = 0;
typedef WTF::HashMap<RenderBlock*, ListHashSet<RenderInline*>*> ContinuationOutlineTableMap;
typedef WTF::HashSet<RenderBlock*> DelayedUpdateScrollInfoSet;
static int gDelayUpdateScrollInfo = 0;
static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
RenderBlock::MarginInfo::MarginInfo(RenderBlock* block, int top, int bottom)
{
m_canCollapseWithChildren = !block->isRenderView() && !block->isRoot() && !block->isPositioned() &&
!block->isFloating() && !block->isTableCell() && !block->hasOverflowClip() && !block->isInlineBlockOrInlineTable();
m_canCollapseTopWithChildren = m_canCollapseWithChildren && (top == 0) && block->style()->marginTopCollapse() != MSEPARATE;
m_canCollapseBottomWithChildren = m_canCollapseWithChildren && (bottom == 0) &&
(block->style()->height().isAuto() && block->style()->height().value() == 0) && block->style()->marginBottomCollapse() != MSEPARATE;
m_quirkContainer = block->isTableCell() || block->isBody() || block->style()->marginTopCollapse() == MDISCARD ||
block->style()->marginBottomCollapse() == MDISCARD;
m_atTopOfBlock = true;
m_atBottomOfBlock = false;
m_posMargin = m_canCollapseTopWithChildren ? block->maxTopMargin(true) : 0;
m_negMargin = m_canCollapseTopWithChildren ? block->maxTopMargin(false) : 0;
m_topQuirk = m_bottomQuirk = m_determinedTopQuirk = false;
}
RenderBlock::RenderBlock(Node* node)
: RenderBox(node)
, m_floatingObjects(0)
, m_positionedObjects(0)
, m_inlineContinuation(0)
, m_maxMargin(0)
, m_lineHeight(-1)
, m_widthForTextAutosizing(-1)
, m_lineCountForTextAutosizing(NOT_SET)
{
setChildrenInline(true);
}
RenderBlock::~RenderBlock()
{
delete m_floatingObjects;
delete m_positionedObjects;
delete m_maxMargin;
if (hasColumns())
delete gColumnInfoMap->take(this);
if (gPercentHeightDescendantsMap) {
if (HashSet<RenderBox*>* descendantSet = gPercentHeightDescendantsMap->take(this)) {
HashSet<RenderBox*>::iterator end = descendantSet->end();
for (HashSet<RenderBox*>::iterator descendant = descendantSet->begin(); descendant != end; ++descendant) {
HashSet<RenderBlock*>* containerSet = gPercentHeightContainerMap->get(*descendant);
ASSERT(containerSet);
if (!containerSet)
continue;
ASSERT(containerSet->contains(this));
containerSet->remove(this);
if (containerSet->isEmpty()) {
gPercentHeightContainerMap->remove(*descendant);
delete containerSet;
}
}
delete descendantSet;
}
}
}
void RenderBlock::destroy()
{
children()->destroyLeftoverChildren();
if (m_inlineContinuation) {
m_inlineContinuation->destroy();
m_inlineContinuation = 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 (isInline() && parent())
parent()->dirtyLinesFromChangedChild(this);
}
m_lineBoxes.deleteLineBoxes(renderArena());
RenderBox::destroy();
}
void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
{
setReplaced(newStyle->isDisplayReplacedType());
if (style() && parent() && diff == StyleDifferenceLayout && style()->position() != newStyle->position()) {
if (newStyle->position() == StaticPosition)
removePositionedObjects(0);
else if (style()->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);
}
}
RenderBox::styleWillChange(diff, newStyle);
}
void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isAnonymousBlock()) {
RefPtr<RenderStyle> newStyle = RenderStyle::create();
newStyle->inheritFrom(style());
newStyle->setDisplay(BLOCK);
child->setStyle(newStyle.release());
}
}
m_lineHeight = -1;
if (!isAnonymous() && document()->usesBeforeAfterRules() && canHaveChildren()) {
updateBeforeAfterContent(BEFORE);
updateBeforeAfterContent(AFTER);
}
updateFirstLetter();
}
void RenderBlock::updateBeforeAfterContent(PseudoId pseudoId)
{
if (parent() && parent()->createsAnonymousWrapper())
return;
return children()->updateBeforeAfterContent(this, pseudoId);
}
void RenderBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
{
if (!beforeChild) {
RenderObject* lastRenderer = lastChild();
if (isAfterContent(lastRenderer))
beforeChild = lastRenderer;
else if (lastRenderer && lastRenderer->isAnonymousBlock() && isAfterContent(lastRenderer->lastChild()))
beforeChild = lastRenderer->lastChild();
}
bool madeBoxesNonInline = false;
if (beforeChild && beforeChild->parent() != this) {
RenderObject* anonymousChild = beforeChild->parent();
ASSERT(anonymousChild);
while (anonymousChild->parent() != this)
anonymousChild = anonymousChild->parent();
ASSERT(anonymousChild->isAnonymous());
if (anonymousChild->isAnonymousBlock()) {
if (newChild->isInline() || beforeChild->parent()->firstChild() != beforeChild)
beforeChild->parent()->addChild(newChild, beforeChild);
else
addChild(newChild, beforeChild->parent());
return;
}
ASSERT(anonymousChild->isTable());
if ((newChild->isTableCol() && newChild->style()->display() == TABLE_COLUMN_GROUP)
|| (newChild->isRenderBlock() && newChild->style()->display() == TABLE_CAPTION)
|| newChild->isTableSection()
|| newChild->isTableRow()
|| newChild->isTableCell()) {
anonymousChild->addChild(newChild, beforeChild);
return;
}
beforeChild = anonymousChild;
}
if (childrenInline() && !newChild->isInline() && !newChild->isFloatingOrPositioned()) {
makeChildrenNonInline(beforeChild);
madeBoxesNonInline = true;
if (beforeChild && beforeChild->parent() != this) {
beforeChild = beforeChild->parent();
ASSERT(beforeChild->isAnonymousBlock());
ASSERT(beforeChild->parent() == this);
}
} else if (!childrenInline() && (newChild->isFloatingOrPositioned() || 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);
if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
}
static void getInlineRun(RenderObject* start, RenderObject* boundary,
RenderObject*& inlineRunStart,
RenderObject*& inlineRunEnd)
{
RenderObject * curr = start;
bool sawInline;
do {
while (curr && !(curr->isInline() || curr->isFloatingOrPositioned()))
curr = curr->nextSibling();
inlineRunStart = inlineRunEnd = curr;
if (!curr)
return;
sawInline = curr->isInline();
curr = curr->nextSibling();
while (curr && (curr->isInline() || curr->isFloatingOrPositioned()) && (curr != boundary)) {
inlineRunEnd = curr;
if (curr->isInline())
sawInline = true;
curr = curr->nextSibling();
}
} while (!sawInline);
}
void RenderBlock::deleteLineBoxTree()
{
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::moveChildTo(RenderObject* to, RenderObjectChildList* toChildList, RenderObject* child)
{
ASSERT(this == child->parent());
toChildList->appendChildNode(to, children()->removeChildNode(this, child, false), false);
}
void RenderBlock::moveChildTo(RenderObject* to, RenderObjectChildList* toChildList, RenderObject* beforeChild, RenderObject* child)
{
ASSERT(this == child->parent());
ASSERT(!beforeChild || to == beforeChild->parent());
toChildList->insertChildNode(to, children()->removeChildNode(this, child, false), beforeChild, false);
}
void RenderBlock::moveAllChildrenTo(RenderObject* to, RenderObjectChildList* toChildList)
{
RenderObject* nextChild = children()->firstChild();
while (nextChild) {
RenderObject* child = nextChild;
nextChild = child->nextSibling();
toChildList->appendChildNode(to, children()->removeChildNode(this, child, false), false);
}
}
void RenderBlock::moveAllChildrenTo(RenderObject* to, RenderObjectChildList* toChildList, RenderObject* beforeChild)
{
ASSERT(!beforeChild || to == beforeChild->parent());
if (!beforeChild) {
moveAllChildrenTo(to, toChildList);
return;
}
RenderObject* nextChild = children()->firstChild();
while (nextChild) {
RenderObject* child = nextChild;
nextChild = child->nextSibling();
toChildList->insertChildNode(to, children()->removeChildNode(this, child, false), beforeChild, false);
}
}
void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
{
ASSERT(isInlineBlockOrInlineTable() || !isInline());
ASSERT(!insertionPoint || insertionPoint->parent() == this);
setChildrenInline(false);
RenderObject *child = firstChild();
if (!child)
return;
deleteLineBoxTree();
while (child) {
RenderObject *inlineRunStart, *inlineRunEnd;
getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
if (!inlineRunStart)
break;
child = inlineRunEnd->nextSibling();
RenderBlock* block = createAnonymousBlock();
children()->insertChildNode(this, block, inlineRunStart);
RenderObject* o = inlineRunStart;
while (o != inlineRunEnd) {
RenderObject* no = o;
o = no->nextSibling();
moveChildTo(block, block->children(), no);
}
moveChildTo(block, block->children(), inlineRunEnd);
}
#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->inlineContinuation())
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);
} else {
if (child->previousSibling())
child->previousSibling()->setNextSibling(child->nextSibling());
if (child->nextSibling())
child->nextSibling()->setPreviousSibling(child->previousSibling());
}
if (child == m_children.firstChild())
m_children.setFirstChild(firstAnChild);
if (child == m_children.lastChild())
m_children.setLastChild(lastAnChild);
child->setParent(0);
child->setPreviousSibling(0);
child->setNextSibling(0);
child->children()->setFirstChild(0);
child->m_next = 0;
child->destroy();
}
void RenderBlock::removeChild(RenderObject* oldChild)
{
RenderObject* prev = oldChild->previousSibling();
RenderObject* next = oldChild->nextSibling();
bool canDeleteAnonymousBlocks = !documentBeingDestroyed() && !isInline() && !oldChild->isInline() &&
(!oldChild->isRenderBlock() || !toRenderBlock(oldChild)->inlineContinuation()) &&
(!prev || (prev->isAnonymousBlock() && prev->childrenInline())) &&
(!next || (next->isAnonymousBlock() && next->childrenInline())) &&
!(prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn());
if (canDeleteAnonymousBlocks && prev && next) {
prev->setNeedsLayoutAndPrefWidthsRecalc();
RenderBlock* nextBlock = toRenderBlock(next);
RenderBlock* prevBlock = toRenderBlock(prev);
nextBlock->moveAllChildrenTo(prevBlock, prevBlock->children());
nextBlock->deleteLineBoxTree();
nextBlock->destroy();
}
RenderBox::removeChild(oldChild);
RenderObject* child = prev ? prev : next;
if (canDeleteAnonymousBlocks && child && !child->previousSibling() && !child->nextSibling() && !isFlexibleBox()) {
setNeedsLayoutAndPrefWidthsRecalc();
RenderBlock* anonBlock = toRenderBlock(children()->removeChildNode(this, child, false));
setChildrenInline(true);
anonBlock->moveAllChildrenTo(this, children());
anonBlock->deleteLineBoxTree();
anonBlock->destroy();
}
if (childrenInline() && !firstChild())
lineBoxes()->deleteLineBoxes(renderArena());
}
bool RenderBlock::isSelfCollapsingBlock() const
{
if (height() > 0
|| isTable() || borderAndPaddingHeight()
|| style()->minHeight().isPositive()
|| style()->marginTopCollapse() == MSEPARATE || style()->marginBottomCollapse() == MSEPARATE)
return false;
bool hasAutoHeight = style()->height().isAuto();
if (style()->height().isPercent() && !style()->htmlHacks()) {
hasAutoHeight = true;
for (RenderBlock* cb = containingBlock(); !cb->isRenderView(); cb = cb->containingBlock()) {
if (cb->style()->height().isFixed() || cb->isTableCell())
hasAutoHeight = false;
}
}
if (hasAutoHeight || ((style()->height().isFixed() || style()->height().isPercent()) && style()->height().isZero())) {
if (childrenInline())
return !firstLineBox();
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (child->isFloatingOrPositioned())
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(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()
{
updateFirstLetter();
layoutBlock(false);
if (hasControlClip() && m_overflow)
clearLayoutOverflow();
}
void RenderBlock::layoutBlock(bool relayoutChildren)
{
ASSERT(needsLayout());
if (isInline() && !isInlineBlockOrInlineTable()) return;
if (!relayoutChildren && layoutOnlyPositionedObjects())
return;
LayoutRepainter repainter(*this, m_everHadLayout && checkForRepaintDuringLayout());
LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasColumns() || hasTransform() || hasReflection());
int oldWidth = width();
int oldColumnWidth = desiredColumnWidth();
calcWidth();
calcColumnWidth();
m_overflow.clear();
if (oldWidth != width() || oldColumnWidth != desiredColumnWidth())
relayoutChildren = true;
clearFloats();
int previousHeight = height();
setHeight(0);
bool isCell = isTableCell();
if (!isCell) {
initMaxMarginValues();
setTopMarginQuirk(style()->marginTop().quirk());
setBottomMarginQuirk(style()->marginBottom().quirk());
Node* n = node();
if (n && n->hasTagName(formTag) && static_cast<HTMLFormElement*>(n)->isMalformed()) {
setMaxBottomMargins(0, 0);
}
}
if (scrollsOverflow()) {
if (style()->overflowX() == OSCROLL)
layer()->setHasHorizontalScrollbar(true);
if (style()->overflowY() == OSCROLL)
layer()->setHasVerticalScrollbar(true);
}
int repaintTop = 0;
int repaintBottom = 0;
int maxFloatBottom = 0;
if (!firstChild() && !isAnonymousBlock())
setChildrenInline(true);
if (childrenInline())
layoutInlineChildren(relayoutChildren, repaintTop, repaintBottom);
else
layoutBlockChildren(relayoutChildren, maxFloatBottom);
int toAdd = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
if (floatBottom() > (height() - toAdd) && expandsToEncloseOverhangingFloats())
setHeight(floatBottom() + toAdd);
int singleColumnBottom = layoutColumns();
int oldHeight = height();
calcHeight();
if (oldHeight != height()) {
if (oldHeight > height() && maxFloatBottom > height() && !childrenInline()) {
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isBlockFlow() && !child->isFloatingOrPositioned()) {
RenderBlock* block = toRenderBlock(child);
if (block->floatBottom() + block->y() > height())
addOverhangingFloats(block, -block->x(), -block->y(), false);
}
}
}
layoutColumns(singleColumnBottom);
}
if (previousHeight != height())
relayoutChildren = true;
if (isRoot() || expandsToEncloseOverhangingFloats())
addOverflowFromFloats();
if (!hasColumns()) {
if (childrenInline())
addOverflowFromInlineChildren();
else
addOverflowFromBlockChildren();
}
addShadowOverflow();
layoutPositionedObjects(relayoutChildren || isRoot());
positionListMarker();
statePusher.pop();
updateScrollInfoAfterLayout();
bool didFullRepaint = repainter.repaintAfterLayout();
if (!didFullRepaint && repaintTop != repaintBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
int repaintLeft = min(leftVisualOverflow(), leftLayoutOverflow());
int repaintRight = max(rightVisualOverflow(), rightLayoutOverflow());
IntRect repaintRect(repaintLeft, repaintTop, repaintRight - repaintLeft, repaintBottom - repaintTop);
repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
if (hasOverflowClip()) {
repaintRect.move(-layer()->scrolledContentOffset());
repaintRect.intersect(IntRect(0, 0, width(), height()));
}
if (!repaintRect.isEmpty()) {
repaintRectangle(repaintRect); if (hasReflection())
repaintRectangle(reflectedRect(repaintRect));
}
}
setNeedsLayout(false);
}
void RenderBlock::addOverflowFromBlockChildren()
{
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
if (!child->isFloatingOrPositioned())
addOverflowFromChild(child);
}
}
void RenderBlock::addOverflowFromFloats()
{
IntRect result;
if (!m_floatingObjects)
return;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for (; (r = it.current()); ++it) {
if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer())
addOverflowFromChild(r->m_renderer, IntSize(r->m_left + r->m_renderer->marginLeft(), r->m_top + r->m_renderer->marginTop()));
}
return;
}
bool RenderBlock::expandsToEncloseOverhangingFloats() const
{
return isInlineBlockOrInlineTable() || isFloatingOrPositioned() || hasOverflowClip() || (parent() && parent()->isFlexibleBox()) || hasColumns() || isTableCell() || isFieldset();
}
void RenderBlock::adjustPositionedBlock(RenderBox* child, const MarginInfo& marginInfo)
{
if (child->style()->hasStaticX()) {
if (style()->direction() == LTR)
child->layer()->setStaticX(borderLeft() + paddingLeft());
else
child->layer()->setStaticX(borderRight() + paddingRight());
}
if (child->style()->hasStaticY()) {
int y = height();
if (!marginInfo.canCollapseWithTop()) {
child->calcVerticalMargins();
int marginTop = child->marginTop();
int collapsedTopPos = marginInfo.posMargin();
int collapsedTopNeg = marginInfo.negMargin();
if (marginTop > 0) {
if (marginTop > collapsedTopPos)
collapsedTopPos = marginTop;
} else {
if (-marginTop > collapsedTopNeg)
collapsedTopNeg = -marginTop;
}
y += (collapsedTopPos - collapsedTopNeg) - marginTop;
}
RenderLayer* childLayer = child->layer();
if (childLayer->staticY() != y) {
child->layer()->setStaticY(y);
child->setChildNeedsLayout(true, false);
}
}
}
void RenderBlock::adjustFloatingBlock(const MarginInfo& marginInfo)
{
int marginOffset = marginInfo.canCollapseWithTop() ? 0 : marginInfo.margin();
setHeight(height() + marginOffset);
positionNewFloats();
setHeight(height() - marginOffset);
}
bool RenderBlock::handleSpecialChild(RenderBox* child, const MarginInfo& marginInfo)
{
return handlePositionedChild(child, marginInfo)
|| handleFloatingChild(child, marginInfo)
|| handleRunInChild(child);
}
bool RenderBlock::handlePositionedChild(RenderBox* child, const MarginInfo& marginInfo)
{
if (child->isPositioned()) {
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;
}
bool RenderBlock::handleRunInChild(RenderBox* child)
{
if (!child->isRunIn() || !child->childrenInline())
return false;
if (!child->isRenderBlock())
return false;
RenderBlock* blockRunIn = toRenderBlock(child);
RenderObject* curr = blockRunIn->nextSibling();
while (curr && curr->isFloatingOrPositioned())
curr = curr->nextSibling();
if (!curr || !curr->isRenderBlock() || !curr->childrenInline() || curr->isRunIn() || curr->isAnonymous())
return false;
RenderBlock* currBlock = toRenderBlock(curr);
children()->removeChildNode(this, blockRunIn);
Node* runInNode = blockRunIn->node();
RenderInline* inlineRunIn = new (renderArena()) RenderInline(runInNode ? runInNode : document());
inlineRunIn->setStyle(blockRunIn->style());
bool runInIsGenerated = child->style()->styleType() == BEFORE || child->style()->styleType() == AFTER;
for (RenderObject* runInChild = blockRunIn->firstChild(); runInChild; runInChild = runInChild->nextSibling()) {
if (runInIsGenerated || (runInChild->style()->styleType() != BEFORE && runInChild->style()->styleType() != AFTER)) {
blockRunIn->children()->removeChildNode(blockRunIn, runInChild, false);
inlineRunIn->addChild(runInChild); }
}
currBlock->children()->insertChildNode(currBlock, inlineRunIn, currBlock->firstChild());
if (runInNode)
runInNode->setRenderer(inlineRunIn);
blockRunIn->deleteLineBoxTree();
blockRunIn->destroy();
return true;
}
int RenderBlock::collapseMargins(RenderBox* child, MarginInfo& marginInfo)
{
int posTop = child->maxTopMargin(true);
int negTop = child->maxTopMargin(false);
if (child->isSelfCollapsingBlock()) {
posTop = max(posTop, child->maxBottomMargin(true));
negTop = max(negTop, child->maxBottomMargin(false));
}
bool topQuirk = child->isTopMarginQuirk() || style()->marginTopCollapse() == MDISCARD;
if (marginInfo.canCollapseWithTop()) {
if (!style()->htmlHacks() || !marginInfo.quirkContainer() || !topQuirk)
setMaxTopMargins(max(posTop, maxTopPosMargin()), max(negTop, maxTopNegMargin()));
if (!marginInfo.determinedTopQuirk() && !topQuirk && (posTop-negTop)) {
setTopMarginQuirk(false);
marginInfo.setDeterminedTopQuirk(true);
}
if (!marginInfo.determinedTopQuirk() && topQuirk && marginTop() == 0)
setTopMarginQuirk(true);
}
if (marginInfo.quirkContainer() && marginInfo.atTopOfBlock() && (posTop - negTop))
marginInfo.setTopQuirk(topQuirk);
int ypos = height();
if (child->isSelfCollapsingBlock()) {
int collapsedTopPos = max(marginInfo.posMargin(), child->maxTopMargin(true));
int collapsedTopNeg = max(marginInfo.negMargin(), child->maxTopMargin(false));
marginInfo.setMargin(collapsedTopPos, collapsedTopNeg);
marginInfo.setPosMarginIfLarger(child->maxBottomMargin(true));
marginInfo.setNegMarginIfLarger(child->maxBottomMargin(false));
if (!marginInfo.canCollapseWithTop())
ypos = height() + collapsedTopPos - collapsedTopNeg;
}
else {
if (child->style()->marginTopCollapse() == MSEPARATE) {
setHeight(height() + marginInfo.margin() + child->marginTop());
ypos = height();
}
else if (!marginInfo.atTopOfBlock() ||
(!marginInfo.canCollapseTopWithChildren()
&& (!style()->htmlHacks() || !marginInfo.quirkContainer() || !marginInfo.topQuirk()))) {
setHeight(height() + max(marginInfo.posMargin(), posTop) - max(marginInfo.negMargin(), negTop));
ypos = height();
}
marginInfo.setPosMargin(child->maxBottomMargin(true));
marginInfo.setNegMargin(child->maxBottomMargin(false));
if (marginInfo.margin())
marginInfo.setBottomQuirk(child->isBottomMarginQuirk() || style()->marginBottomCollapse() == MDISCARD);
}
return ypos;
}
int RenderBlock::clearFloatsIfNeeded(RenderBox* child, MarginInfo& marginInfo, int oldTopPosMargin, int oldTopNegMargin, int yPos)
{
int 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->isFloatingOrPositioned())
atBottomOfBlock = false;
}
if (atBottomOfBlock) {
marginInfo.setPosMargin(child->maxBottomMargin(true));
marginInfo.setNegMargin(child->maxBottomMargin(false));
} else {
marginInfo.setPosMargin(max(child->maxTopMargin(true), child->maxBottomMargin(true)));
marginInfo.setNegMargin(max(child->maxTopMargin(false), child->maxBottomMargin(false)));
}
setHeight(child->y() - max(0, marginInfo.margin()));
} else
setHeight(height() + heightIncrease);
if (marginInfo.canCollapseWithTop()) {
setMaxTopMargins(oldTopPosMargin, oldTopNegMargin);
marginInfo.setAtTopOfBlock(false);
}
return yPos + heightIncrease;
}
int RenderBlock::estimateVerticalPosition(RenderBox* child, const MarginInfo& marginInfo)
{
int yPosEstimate = height();
if (!marginInfo.canCollapseWithTop()) {
int childMarginTop = child->selfNeedsLayout() ? child->marginTop() : child->collapsedMarginTop();
yPosEstimate += max(marginInfo.margin(), childMarginTop);
}
yPosEstimate += getClearDelta(child, yPosEstimate);
return yPosEstimate;
}
void RenderBlock::determineHorizontalPosition(RenderBox* child)
{
if (style()->direction() == LTR) {
int xPos = borderLeft() + paddingLeft();
int chPos = xPos + child->marginLeft();
if (child->avoidsFloats()) {
int leftOff = leftOffset(height(), false);
if (style()->textAlign() != WEBKIT_CENTER && child->style()->marginLeft().type() != Auto) {
if (child->marginLeft() < 0)
leftOff += child->marginLeft();
chPos = max(chPos, leftOff); }
else if (leftOff != xPos) {
child->calcHorizontalMargins(child->style()->marginLeft(), child->style()->marginRight(), lineWidth(child->y(), false));
chPos = leftOff + child->marginLeft();
}
}
view()->addLayoutDelta(IntSize(child->x() - chPos, 0));
child->setLocation(chPos, child->y());
} else {
int xPos = width() - borderRight() - paddingRight() - verticalScrollbarWidth();
int chPos = xPos - (child->width() + child->marginRight());
if (child->avoidsFloats()) {
int rightOff = rightOffset(height(), false);
if (style()->textAlign() != WEBKIT_CENTER && child->style()->marginRight().type() != Auto) {
if (child->marginRight() < 0)
rightOff -= child->marginRight();
chPos = min(chPos, rightOff - child->width()); } else if (rightOff != xPos) {
child->calcHorizontalMargins(child->style()->marginLeft(), child->style()->marginRight(), lineWidth(child->y(), false));
chPos = rightOff - child->marginRight() - child->width();
}
}
view()->addLayoutDelta(IntSize(child->x() - chPos, 0));
child->setLocation(chPos, child->y());
}
}
void RenderBlock::setCollapsedBottomMargin(const MarginInfo& marginInfo)
{
if (marginInfo.canCollapseWithBottom() && !marginInfo.canCollapseWithTop()) {
setMaxBottomMargins(max(maxBottomPosMargin(), marginInfo.posMargin()), max(maxBottomNegMargin(), marginInfo.negMargin()));
if (!marginInfo.bottomQuirk())
setBottomMarginQuirk(false);
if (marginInfo.bottomQuirk() && marginBottom() == 0)
setBottomMarginQuirk(true);
}
}
void RenderBlock::handleBottomOfBlock(int top, int bottom, MarginInfo& marginInfo)
{
marginInfo.setAtBottomOfBlock(true);
if (!marginInfo.canCollapseWithBottom() && !marginInfo.canCollapseWithTop()
&& (!style()->htmlHacks() || !marginInfo.quirkContainer() || !marginInfo.bottomQuirk()))
setHeight(height() + marginInfo.margin());
setHeight(height() + bottom);
setHeight(max(height(), top + bottom));
setCollapsedBottomMargin(marginInfo);
}
void RenderBlock::layoutBlockChildren(bool relayoutChildren, int& maxFloatBottom)
{
if (gPercentHeightDescendantsMap) {
if (HashSet<RenderBox*>* descendants = gPercentHeightDescendantsMap->get(this)) {
HashSet<RenderBox*>::iterator end = descendants->end();
for (HashSet<RenderBox*>::iterator it = descendants->begin(); it != end; ++it) {
RenderBox* box = *it;
while (box != this) {
if (box->normalChildNeedsLayout())
break;
box->setChildNeedsLayout(true, false);
box = box->containingBlock();
ASSERT(box);
if (!box)
break;
}
}
}
}
int top = borderTop() + paddingTop();
int bottom = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
setHeight(top);
MarginInfo marginInfo(this, top, bottom);
RenderObject* legend = layoutLegend(relayoutChildren);
int previousFloatBottom = 0;
maxFloatBottom = 0;
RenderBox* next = firstChildBox();
while (next) {
RenderBox* child = next;
next = child->nextSiblingBox();
if (legend == child)
continue;
if (relayoutChildren || ((child->style()->height().isPercent() || child->style()->minHeight().isPercent() || child->style()->maxHeight().isPercent()) && !isRenderView()))
child->setChildNeedsLayout(true, false);
if (relayoutChildren && (child->style()->paddingLeft().isPercent() || child->style()->paddingRight().isPercent()))
child->setPrefWidthsDirty(true, false);
if (handleSpecialChild(child, marginInfo))
continue;
layoutBlockChild(child, marginInfo, previousFloatBottom, maxFloatBottom);
}
handleBottomOfBlock(top, bottom, marginInfo);
}
void RenderBlock::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo, int& previousFloatBottom, int& maxFloatBottom)
{
int oldTopPosMargin = maxTopPosMargin();
int oldTopNegMargin = maxTopNegMargin();
child->calcVerticalMargins();
if (child->style()->marginTopCollapse() == MSEPARATE) {
marginInfo.setAtTopOfBlock(false);
marginInfo.clearMargin();
}
int yPosEstimate = estimateVerticalPosition(child, marginInfo);
IntRect oldRect(child->x(), child->y() , child->width(), child->height());
#ifndef NDEBUG
IntSize oldLayoutDelta = view()->layoutDelta();
#endif
view()->addLayoutDelta(IntSize(0, child->y() - yPosEstimate));
child->setLocation(child->x(), yPosEstimate);
bool markDescendantsWithFloats = false;
if (yPosEstimate != oldRect.y() && !child->avoidsFloats() && child->isBlockFlow() && toRenderBlock(child)->containsFloats())
markDescendantsWithFloats = true;
else if (!child->avoidsFloats() || child->shrinkToAvoidFloats()) {
int fb = max(previousFloatBottom, floatBottom());
if (fb > yPosEstimate)
markDescendantsWithFloats = true;
}
if (child->isRenderBlock()) {
if (markDescendantsWithFloats)
toRenderBlock(child)->markAllDescendantsWithFloatsForLayout();
previousFloatBottom = max(previousFloatBottom, oldRect.y() + toRenderBlock(child)->floatBottom());
}
bool childHadLayout = child->m_everHadLayout;
bool childNeededLayout = child->needsLayout();
if (childNeededLayout)
child->layout();
int yBeforeClear = collapseMargins(child, marginInfo);
int yAfterClear = clearFloatsIfNeeded(child, marginInfo, oldTopPosMargin, oldTopNegMargin, yBeforeClear);
view()->addLayoutDelta(IntSize(0, yPosEstimate - yAfterClear));
child->setLocation(child->x(), yAfterClear);
if (yAfterClear != yPosEstimate) {
if (child->shrinkToAvoidFloats()) {
child->setChildNeedsLayout(true, false);
}
if (!child->avoidsFloats() && child->isBlockFlow() && toRenderBlock(child)->containsFloats())
toRenderBlock(child)->markAllDescendantsWithFloatsForLayout();
child->layoutIfNeeded();
}
if (marginInfo.atTopOfBlock() && !child->isSelfCollapsingBlock())
marginInfo.setAtTopOfBlock(false);
determineHorizontalPosition(child);
setHeight(height() + child->height());
if (child->style()->marginBottomCollapse() == MSEPARATE) {
setHeight(height() + child->marginBottom());
marginInfo.clearMargin();
}
if (child->isBlockFlow() && toRenderBlock(child)->containsFloats())
maxFloatBottom = max(maxFloatBottom, addOverhangingFloats(toRenderBlock(child), -child->x(), -child->y(), !childNeededLayout));
IntSize 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);
}
ASSERT(oldLayoutDelta == view()->layoutDelta());
}
bool RenderBlock::layoutOnlyPositionedObjects()
{
if (!posChildNeedsLayout() || normalChildNeedsLayout() || selfNeedsLayout())
return false;
LayoutStateMaintainer statePusher(view(), this, IntSize(x(), y()), hasColumns() || hasTransform() || hasReflection());
if (needsPositionedMovementLayout()) {
tryLayoutDoingPositionedMovementOnly();
if (needsLayout())
return false;
}
layoutPositionedObjects(false);
statePusher.pop();
updateScrollInfoAfterLayout();
setNeedsLayout(false);
return true;
}
void RenderBlock::layoutPositionedObjects(bool relayoutChildren)
{
if (m_positionedObjects) {
RenderBox* r;
Iterator end = m_positionedObjects->end();
for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
r = *it;
if (relayoutChildren || (r->style()->hasStaticY() && r->parent() != this && r->parent()->isBlockFlow()))
r->setChildNeedsLayout(true, false);
r->setPrefWidthsDirty(true, false);
if (r->needsPositionedMovementLayoutOnly())
r->tryLayoutDoingPositionedMovementOnly();
r->layoutIfNeeded();
}
}
}
void RenderBlock::markPositionedObjectsForLayout()
{
if (m_positionedObjects) {
RenderBox* r;
Iterator end = m_positionedObjects->end();
for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
r = *it;
r->setChildNeedsLayout(true);
}
}
}
void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
{
if (hasOverhangingFloats()) {
ASSERT(m_floatingObjects);
if (!m_floatingObjects)
return;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
view()->disableLayoutState();
for ( ; (r = it.current()); ++it) {
if (r->m_bottom > height() && ((paintAllDescendants && r->m_renderer->isDescendantOf(this)) || r->m_shouldPaint) && !r->m_renderer->hasSelfPaintingLayer()) {
r->m_renderer->repaint();
r->m_renderer->repaintOverhangingFloats();
}
}
view()->enableLayoutState();
}
}
void RenderBlock::paint(PaintInfo& paintInfo, int tx, int ty)
{
tx += x();
ty += y();
PaintPhase phase = paintInfo.phase;
if (!isRoot()) {
IntRect overflowBox = visibleOverflowRect();
overflowBox.inflate(maximalOutlineSize(paintInfo.phase));
overflowBox.move(tx, ty);
if (!overflowBox.intersects(paintInfo.rect))
return;
}
bool pushedClip = pushContentsClip(paintInfo, tx, ty);
paintObject(paintInfo, tx, ty);
if (pushedClip)
popContentsClip(paintInfo, phase, tx, ty);
if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && shouldPaintWithinRoot(paintInfo))
layer()->paintOverflowControls(paintInfo.context, tx, ty, paintInfo.rect);
}
void RenderBlock::paintColumnRules(PaintInfo& paintInfo, int tx, int ty)
{
const Color& ruleColor = style()->visitedDependentColor(CSSPropertyWebkitColumnRuleColor);
bool ruleTransparent = style()->columnRuleIsTransparent();
EBorderStyle ruleStyle = style()->columnRuleStyle();
int ruleWidth = style()->columnRuleWidth();
int colGap = columnGap();
bool renderRule = ruleStyle > BHIDDEN && !ruleTransparent && ruleWidth <= colGap;
if (!renderRule)
return;
int currXOffset = 0;
int ruleAdd = borderLeft() + paddingLeft();
int ruleX = 0;
Vector<IntRect>* colRects = columnRects();
unsigned colCount = colRects->size();
for (unsigned i = 0; i < colCount; i++) {
IntRect colRect = colRects->at(i);
if (style()->direction() == LTR) {
ruleX += colRect.width() + colGap / 2;
currXOffset += colRect.width() + colGap;
} else {
ruleX -= (colRect.width() + colGap / 2);
currXOffset -= (colRect.width() + colGap);
}
if (i < colCount - 1) {
int ruleStart = tx + ruleX - ruleWidth / 2 + ruleAdd;
int ruleEnd = ruleStart + ruleWidth;
int ruleTop = ty + borderTop() + paddingTop();
int ruleBottom = ruleTop + contentHeight();
drawLineForBoxSide(paintInfo.context, ruleStart, ruleTop, ruleEnd, ruleBottom,
style()->direction() == LTR ? BSLeft : BSRight, ruleColor, ruleStyle, 0, 0);
}
ruleX = currXOffset;
}
}
void RenderBlock::paintColumnContents(PaintInfo& paintInfo, int tx, int ty, bool paintingFloats)
{
GraphicsContext* context = paintInfo.context;
int currXOffset = 0;
int currYOffset = 0;
int colGap = columnGap();
Vector<IntRect>* colRects = columnRects();
unsigned colCount = colRects->size();
for (unsigned i = 0; i < colCount; i++) {
IntRect colRect = colRects->at(i);
colRect.move(tx, ty);
context->save();
context->clip(colRect);
PaintInfo info(paintInfo);
info.rect.intersect(colRect);
int finalX = tx + currXOffset;
int finalY = ty + currYOffset;
if (paintingFloats)
paintFloats(info, finalX, finalY, paintInfo.phase == PaintPhaseSelection || paintInfo.phase == PaintPhaseTextClip);
else
paintContents(info, finalX, finalY);
if (style()->direction() == LTR)
currXOffset += colRect.width() + colGap;
else
currXOffset -= (colRect.width() + colGap);
currYOffset -= colRect.height();
context->restore();
}
}
void RenderBlock::paintContents(PaintInfo& paintInfo, int tx, int ty)
{
if (document()->didLayoutWithPendingStylesheets() && !isRenderView())
return;
if (childrenInline())
m_lineBoxes.paint(this, paintInfo, tx, ty);
else
paintChildren(paintInfo, tx, ty);
}
void RenderBlock::paintChildren(PaintInfo& paintInfo, int tx, int ty)
{
PaintPhase newPhase = (paintInfo.phase == PaintPhaseChildOutlines) ? PaintPhaseOutline : paintInfo.phase;
newPhase = (newPhase == PaintPhaseChildBlockBackgrounds) ? PaintPhaseChildBlockBackground : newPhase;
PaintInfo info(paintInfo);
info.phase = newPhase;
info.paintingRoot = paintingRootForChildren(paintInfo);
bool checkPageBreaks = document()->printing();
bool checkColumnBreaks = !checkPageBreaks && !view()->printRect().isEmpty();
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
bool checkBeforeAlways = !childrenInline() && (checkPageBreaks && child->style()->pageBreakBefore() == PBALWAYS || checkColumnBreaks && child->style()->columnBreakBefore() == PBALWAYS);
if (checkBeforeAlways
&& (ty + child->y()) > paintInfo.rect.y()
&& (ty + child->y()) < paintInfo.rect.bottom()) {
view()->setBestTruncatedAt(ty + child->y(), this, true);
return;
}
bool checkInsideAvoid = !childrenInline() && (checkPageBreaks && child->style()->pageBreakInside() == PBAVOID || checkColumnBreaks && child->style()->columnBreakInside() == PBAVOID);
if (checkInsideAvoid
&& ty + child->y() > paintInfo.rect.y()
&& ty + child->y() < paintInfo.rect.bottom()
&& ty + child->y() + child->height() > paintInfo.rect.bottom()) {
view()->setBestTruncatedAt(ty + child->y(), this, true);
return;
}
if (!child->hasSelfPaintingLayer() && !child->isFloating())
child->paint(info, tx, ty);
bool checkAfterAlways = !childrenInline() && (checkPageBreaks && child->style()->pageBreakAfter() == PBALWAYS || checkColumnBreaks && child->style()->columnBreakAfter() == PBALWAYS);
if (checkAfterAlways
&& (ty + child->y() + child->height()) > paintInfo.rect.y()
&& (ty + child->y() + child->height()) < paintInfo.rect.bottom()) {
view()->setBestTruncatedAt(ty + child->y() + child->height() + max(0, child->collapsedMarginBottom()), this, true);
return;
}
}
}
void RenderBlock::paintCaret(PaintInfo& paintInfo, int tx, int ty, CaretType type)
{
SelectionController* selection = type == CursorCaret ? document()->frame()->selection() : document()->frame()->dragCaretController();
bool caretBrowsing = document()->frame()->settings() && document()->frame()->settings()->caretBrowsingEnabled();
RenderObject* caretPainter = selection->caretRenderer();
if (caretPainter == this && (selection->isContentEditable() || caretBrowsing)) {
offsetForContents(tx, ty);
if (type == CursorCaret)
document()->frame()->selection()->paintCaret(paintInfo.context, tx, ty, paintInfo.rect);
else
document()->frame()->paintDragCaret(paintInfo.context, tx, ty, paintInfo.rect);
}
}
void RenderBlock::paintObject(PaintInfo& paintInfo, int tx, int ty)
{
PaintPhase paintPhase = paintInfo.phase;
if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
if (hasBoxDecorations())
paintBoxDecorations(paintInfo, tx, ty);
if (hasColumns())
paintColumnRules(paintInfo, tx, ty);
}
if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
paintMask(paintInfo, tx, ty);
return;
}
if (paintPhase == PaintPhaseBlockBackground)
return;
int scrolledX = tx;
int scrolledY = ty;
if (hasOverflowClip()) {
IntSize offset = layer()->scrolledContentOffset();
scrolledX -= offset.width();
scrolledY -= offset.height();
}
if (paintPhase != PaintPhaseSelfOutline) {
if (hasColumns())
paintColumnContents(paintInfo, scrolledX, scrolledY);
else
paintContents(paintInfo, scrolledX, scrolledY);
}
bool isPrinting = document()->printing();
if (!isPrinting && !hasColumns())
paintSelection(paintInfo, scrolledX, scrolledY);
if (paintPhase == PaintPhaseFloat || paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip) {
if (hasColumns())
paintColumnContents(paintInfo, scrolledX, scrolledY, true);
else
paintFloats(paintInfo, scrolledX, scrolledY, paintPhase == PaintPhaseSelection || paintPhase == PaintPhaseTextClip);
}
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseSelfOutline) && hasOutline() && style()->visibility() == VISIBLE)
paintOutline(paintInfo.context, tx, ty, width(), height());
if ((paintPhase == PaintPhaseOutline || paintPhase == PaintPhaseChildOutlines)) {
RenderInline* inlineCont = inlineContinuation();
if (inlineCont && inlineCont->hasOutline() && inlineCont->style()->visibility() == VISIBLE) {
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, tx - x() + inlineRenderer->containingBlock()->x(),
ty - y() + inlineRenderer->containingBlock()->y());
}
paintContinuationOutlines(paintInfo, tx, ty);
}
if (paintPhase == PaintPhaseForeground) {
paintCaret(paintInfo, scrolledX, scrolledY, CursorCaret);
paintCaret(paintInfo, scrolledX, scrolledY, DragCaret);
}
}
void RenderBlock::paintFloats(PaintInfo& paintInfo, int tx, int ty, bool preservePhase)
{
if (!m_floatingObjects)
return;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for (; (r = it.current()); ++it) {
if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer()) {
PaintInfo currentPaintInfo(paintInfo);
currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
int currentTX = tx + r->m_left - r->m_renderer->x() + r->m_renderer->marginLeft();
int currentTY = ty + r->m_top - r->m_renderer->y() + r->m_renderer->marginTop();
r->m_renderer->paint(currentPaintInfo, currentTX, currentTY);
if (!preservePhase) {
currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
r->m_renderer->paint(currentPaintInfo, currentTX, currentTY);
currentPaintInfo.phase = PaintPhaseFloat;
r->m_renderer->paint(currentPaintInfo, currentTX, currentTY);
currentPaintInfo.phase = PaintPhaseForeground;
r->m_renderer->paint(currentPaintInfo, currentTX, currentTY);
currentPaintInfo.phase = PaintPhaseOutline;
r->m_renderer->paint(currentPaintInfo, currentTX, currentTY);
}
}
}
}
void RenderBlock::paintEllipsisBoxes(PaintInfo& paintInfo, int tx, int ty)
{
if (!shouldPaintWithinRoot(paintInfo) || !firstLineBox())
return;
if (style()->visibility() == VISIBLE && paintInfo.phase == PaintPhaseForeground) {
int yPos = ty + firstLineBox()->y();
int h = lastLineBox()->y() + lastLineBox()->height() - firstLineBox()->y();
if (yPos >= paintInfo.rect.bottom() || yPos + h <= paintInfo.rect.y())
return;
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
yPos = ty + curr->y();
h = curr->height();
if (curr->ellipsisBox() && yPos < paintInfo.rect.bottom() && yPos + h > paintInfo.rect.y())
curr->paintEllipsisBox(paintInfo, tx, ty);
}
}
}
static ContinuationOutlineTableMap* continuationOutlineTable()
{
DEFINE_STATIC_LOCAL(ContinuationOutlineTableMap, table, ());
return &table;
}
void RenderBlock::addContinuationWithOutline(RenderInline* flow)
{
ASSERT(!flow->layer() && !flow->isInlineContinuation());
ContinuationOutlineTableMap* table = continuationOutlineTable();
ListHashSet<RenderInline*>* continuations = table->get(this);
if (!continuations) {
continuations = new ListHashSet<RenderInline*>;
table->set(this, continuations);
}
continuations->add(flow);
}
void RenderBlock::paintContinuationOutlines(PaintInfo& info, int tx, int ty)
{
ContinuationOutlineTableMap* table = continuationOutlineTable();
if (table->isEmpty())
return;
ListHashSet<RenderInline*>* continuations = table->get(this);
if (!continuations)
return;
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()) {
tx += block->x();
ty += block->y();
}
ASSERT(block);
flow->paintOutline(info.context, tx, ty);
}
delete continuations;
table->remove(this);
}
void RenderBlock::setSelectionState(SelectionState s)
{
if (selectionState() == s)
return;
if (s == SelectionInside && selectionState() != SelectionNone)
return;
if ((s == SelectionStart && selectionState() == SelectionEnd) ||
(s == SelectionEnd && selectionState() == SelectionStart))
RenderBox::setSelectionState(SelectionBoth);
else
RenderBox::setSelectionState(s);
RenderBlock* cb = containingBlock();
if (cb && !cb->isRenderView())
cb->setSelectionState(s);
}
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() || isRelPositioned() ||
isFloatingOrPositioned() || isTableCell() || isInlineBlockOrInlineTable() || hasTransform() ||
hasReflection() || hasMask())
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);
IntPoint offsetFromRepaintContainer = roundedIntPoint(transformState.mappedPoint());
if (hasOverflowClip())
offsetFromRepaintContainer -= layer()->scrolledContentOffset();
int lastTop = 0;
int lastLeft = leftSelectionOffset(this, lastTop);
int lastRight = rightSelectionOffset(this, lastTop);
return fillSelectionGaps(this, offsetFromRepaintContainer.x(), offsetFromRepaintContainer.y(), offsetFromRepaintContainer.x(), offsetFromRepaintContainer.y(), lastTop, lastLeft, lastRight);
}
void RenderBlock::paintSelection(PaintInfo& paintInfo, int tx, int ty)
{
UNUSED_PARAM(paintInfo);
UNUSED_PARAM(tx);
UNUSED_PARAM(ty);
return;
}
#ifndef BUILDING_ON_TIGER
static void clipOutPositionedObjects(const RenderObject::PaintInfo* paintInfo, int tx, int ty, RenderBlock::PositionedObjectsListHashSet* positionedObjects)
{
if (!positionedObjects)
return;
RenderBlock::PositionedObjectsListHashSet::const_iterator end = positionedObjects->end();
for (RenderBlock::PositionedObjectsListHashSet::const_iterator it = positionedObjects->begin(); it != end; ++it) {
RenderBox* r = *it;
paintInfo->context->clipOut(IntRect(tx + r->x(), ty + r->y(), r->width(), r->height()));
}
}
#endif
GapRects RenderBlock::fillSelectionGaps(RenderBlock* rootBlock, int blockX, int blockY, int tx, int ty,
int& lastTop, int& lastLeft, int& lastRight, const PaintInfo* paintInfo)
{
#ifndef BUILDING_ON_TIGER
if (paintInfo) {
clipOutPositionedObjects(paintInfo, tx, ty, m_positionedObjects);
if (isBody() || isRoot()) for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
clipOutPositionedObjects(paintInfo, cb->x(), cb->y(), cb->m_positionedObjects);
if (m_floatingObjects) {
for (DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects); it.current(); ++it) {
FloatingObject* r = it.current();
paintInfo->context->clipOut(IntRect(tx + r->m_left + r->m_renderer->marginLeft(),
ty + r->m_top + r->m_renderer->marginTop(),
r->m_renderer->width(), r->m_renderer->height()));
}
}
}
#endif
GapRects result;
if (!isBlockFlow()) return result;
if (hasColumns() || hasTransform()) {
lastTop = (ty - blockY) + height();
lastLeft = leftSelectionOffset(rootBlock, height());
lastRight = rightSelectionOffset(rootBlock, height());
return result;
}
if (childrenInline())
result = fillInlineSelectionGaps(rootBlock, blockX, blockY, tx, ty, lastTop, lastLeft, lastRight, paintInfo);
else
result = fillBlockSelectionGaps(rootBlock, blockX, blockY, tx, ty, lastTop, lastLeft, lastRight, paintInfo);
if (rootBlock == this && (selectionState() != SelectionBoth && selectionState() != SelectionEnd))
result.uniteCenter(fillVerticalSelectionGap(lastTop, lastLeft, lastRight, ty + height(),
rootBlock, blockX, blockY, paintInfo));
return result;
}
GapRects RenderBlock::fillInlineSelectionGaps(RenderBlock* rootBlock, int blockX, int blockY, int tx, int ty,
int& lastTop, int& lastLeft, int& lastRight, const PaintInfo* paintInfo)
{
GapRects result;
bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
if (!firstLineBox()) {
if (containsStart) {
lastTop = (ty - blockY) + height();
lastLeft = leftSelectionOffset(rootBlock, height());
lastRight = rightSelectionOffset(rootBlock, height());
}
return result;
}
RootInlineBox* lastSelectedLine = 0;
RootInlineBox* curr;
for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
int selTop = curr->selectionTop();
int selHeight = curr->selectionHeight();
if (!containsStart && !lastSelectedLine &&
selectionState() != SelectionStart && selectionState() != SelectionBoth)
result.uniteCenter(fillVerticalSelectionGap(lastTop, lastLeft, lastRight, ty + selTop,
rootBlock, blockX, blockY, paintInfo));
if (!paintInfo || (ty + selTop < paintInfo->rect.bottom() && ty + selTop + selHeight > paintInfo->rect.y()))
result.unite(curr->fillLineSelectionGap(selTop, selHeight, rootBlock, blockX, blockY, tx, ty, paintInfo));
lastSelectedLine = curr;
}
if (containsStart && !lastSelectedLine)
lastSelectedLine = lastRootBox();
if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
lastTop = (ty - blockY) + lastSelectedLine->selectionBottom();
lastLeft = leftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
lastRight = rightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
}
return result;
}
GapRects RenderBlock::fillBlockSelectionGaps(RenderBlock* rootBlock, int blockX, int blockY, int tx, int ty,
int& lastTop, int& lastLeft, int& lastRight, 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->isFloatingOrPositioned())
continue;
if (curr->isRelPositioned() && curr->hasLayer()) {
IntSize relOffset = curr->layer()->relativePositionOffset();
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(fillVerticalSelectionGap(lastTop, lastLeft, lastRight,
ty + curr->y(), rootBlock, blockX, blockY, paintInfo));
if (paintsOwnSelection && (childState == SelectionStart || sawSelectionEnd))
childState = SelectionNone;
bool leftGap, rightGap;
getHorizontalSelectionGapInfo(childState, leftGap, rightGap);
if (leftGap)
result.uniteLeft(fillLeftSelectionGap(this, curr->x(), curr->y(), curr->height(), rootBlock, blockX, blockY, tx, ty, paintInfo));
if (rightGap)
result.uniteRight(fillRightSelectionGap(this, curr->x() + curr->width(), curr->y(), curr->height(), rootBlock, blockX, blockY, tx, ty, paintInfo));
lastTop = (ty - blockY) + (curr->y() + curr->height());
lastLeft = leftSelectionOffset(rootBlock, curr->y() + curr->height());
lastRight = rightSelectionOffset(rootBlock, curr->y() + curr->height());
} else if (childState != SelectionNone)
result.unite(toRenderBlock(curr)->fillSelectionGaps(rootBlock, blockX, blockY, tx + curr->x(), ty + curr->y(),
lastTop, lastLeft, lastRight, paintInfo));
}
return result;
}
IntRect RenderBlock::fillHorizontalSelectionGap(RenderObject* selObj, int xPos, int yPos, int width, int height, const PaintInfo* paintInfo)
{
if (width <= 0 || height <= 0)
return IntRect();
IntRect gapRect(xPos, yPos, width, height);
if (paintInfo && selObj->style()->visibility() == VISIBLE)
paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
return gapRect;
}
IntRect RenderBlock::fillVerticalSelectionGap(int lastTop, int lastLeft, int lastRight, int bottomY, RenderBlock* rootBlock,
int blockX, int blockY, const PaintInfo* paintInfo)
{
int top = blockY + lastTop;
int height = bottomY - top;
if (height <= 0)
return IntRect();
int left = blockX + max(lastLeft, leftSelectionOffset(rootBlock, bottomY));
int right = blockX + min(lastRight, rightSelectionOffset(rootBlock, bottomY));
int width = right - left;
if (width <= 0)
return IntRect();
IntRect gapRect(left, top, width, height);
if (paintInfo)
paintInfo->context->fillRect(gapRect, selectionBackgroundColor(), style()->colorSpace());
return gapRect;
}
IntRect RenderBlock::fillLeftSelectionGap(RenderObject* selObj, int xPos, int yPos, int height, RenderBlock* rootBlock,
int blockX, int , int tx, int ty, const PaintInfo* paintInfo)
{
int top = yPos + ty;
int left = blockX + max(leftSelectionOffset(rootBlock, yPos), leftSelectionOffset(rootBlock, yPos + height));
int right = min(xPos + tx, blockX + min(rightSelectionOffset(rootBlock, yPos), rightSelectionOffset(rootBlock, yPos + height)));
int width = right - left;
if (width <= 0)
return IntRect();
IntRect gapRect(left, top, width, height);
if (paintInfo)
paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
return gapRect;
}
IntRect RenderBlock::fillRightSelectionGap(RenderObject* selObj, int xPos, int yPos, int height, RenderBlock* rootBlock,
int blockX, int , int tx, int ty, const PaintInfo* paintInfo)
{
int left = max(xPos + tx, blockX + max(leftSelectionOffset(rootBlock, yPos), leftSelectionOffset(rootBlock, yPos + height)));
int top = yPos + ty;
int right = blockX + min(rightSelectionOffset(rootBlock, yPos), rightSelectionOffset(rootBlock, yPos + height));
int width = right - left;
if (width <= 0)
return IntRect();
IntRect gapRect(left, top, width, height);
if (paintInfo)
paintInfo->context->fillRect(gapRect, selObj->selectionBackgroundColor(), selObj->style()->colorSpace());
return gapRect;
}
void RenderBlock::getHorizontalSelectionGapInfo(SelectionState state, bool& leftGap, bool& rightGap)
{
bool ltr = style()->direction() == LTR;
leftGap = (state == RenderObject::SelectionInside) ||
(state == RenderObject::SelectionEnd && ltr) ||
(state == RenderObject::SelectionStart && !ltr);
rightGap = (state == RenderObject::SelectionInside) ||
(state == RenderObject::SelectionStart && ltr) ||
(state == RenderObject::SelectionEnd && !ltr);
}
int RenderBlock::leftSelectionOffset(RenderBlock* rootBlock, int yPos)
{
int left = leftOffset(yPos, false);
if (left == borderLeft() + paddingLeft()) {
if (rootBlock != this)
return containingBlock()->leftSelectionOffset(rootBlock, yPos + y());
return left;
}
else {
RenderBlock* cb = this;
while (cb != rootBlock) {
left += cb->x();
cb = cb->containingBlock();
}
}
return left;
}
int RenderBlock::rightSelectionOffset(RenderBlock* rootBlock, int yPos)
{
int right = rightOffset(yPos, false);
if (right == (contentWidth() + (borderLeft() + paddingLeft()))) {
if (rootBlock != this)
return containingBlock()->rightSelectionOffset(rootBlock, yPos + y());
return right;
}
else {
RenderBlock* cb = this;
while (cb != rootBlock) {
right += cb->x();
cb = cb->containingBlock();
}
}
return right;
}
void RenderBlock::insertPositionedObject(RenderBox* o)
{
if (!m_positionedObjects)
m_positionedObjects = new RenderBlock::PositionedObjectsListHashSet;
m_positionedObjects->add(o);
}
void RenderBlock::removePositionedObject(RenderBox* o)
{
if (m_positionedObjects)
m_positionedObjects->remove(o);
}
void RenderBlock::removePositionedObjects(RenderBlock* o)
{
if (!m_positionedObjects)
return;
RenderBox* r;
Iterator end = m_positionedObjects->end();
Vector<RenderBox*, 16> deadObjects;
for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
r = *it;
if (!o || r->isDescendantOf(o)) {
if (o)
r->setChildNeedsLayout(true, false);
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++)
m_positionedObjects->remove(deadObjects.at(i));
}
void RenderBlock::insertFloatingObject(RenderBox* o)
{
ASSERT(o->isFloating());
if (!m_floatingObjects) {
m_floatingObjects = new DeprecatedPtrList<FloatingObject>;
m_floatingObjects->setAutoDelete(true);
} else {
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
FloatingObject* f;
while ( (f = it.current()) ) {
if (f->m_renderer == o) return;
++it;
}
}
o->layoutIfNeeded();
FloatingObject* newObj = new FloatingObject(o->style()->floating() == FLEFT ? FloatingObject::FloatLeft : FloatingObject::FloatRight);
newObj->m_top = -1;
newObj->m_bottom = -1;
newObj->m_width = o->width() + o->marginLeft() + o->marginRight();
newObj->m_shouldPaint = !o->hasSelfPaintingLayer(); newObj->m_isDescendant = true;
newObj->m_renderer = o;
m_floatingObjects->append(newObj);
}
void RenderBlock::removeFloatingObject(RenderBox* o)
{
if (m_floatingObjects) {
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
while (it.current()) {
if (it.current()->m_renderer == o) {
if (childrenInline()) {
int bottom = it.current()->m_bottom;
bottom = max(bottom, it.current()->m_top + 1);
markLinesDirtyInVerticalRange(0, bottom);
}
m_floatingObjects->removeRef(it.current());
}
++it;
}
}
}
bool RenderBlock::positionNewFloats()
{
if (!m_floatingObjects)
return false;
FloatingObject* f = m_floatingObjects->last();
if (!f || f->m_top != -1)
return false;
FloatingObject* lastFloat = m_floatingObjects->getPrev();
while (lastFloat && lastFloat->m_top == -1) {
f = m_floatingObjects->prev();
lastFloat = m_floatingObjects->getPrev();
}
int y = height();
if (lastFloat)
y = max(lastFloat->m_top, y);
while (f) {
if (f->m_renderer->containingBlock() != this) {
f = m_floatingObjects->next();
continue;
}
RenderBox* o = f->m_renderer;
int _height = o->height() + o->marginTop() + o->marginBottom();
int ro = rightOffset(); int lo = leftOffset(); int fwidth = f->m_width; if (ro - lo < fwidth)
fwidth = ro - lo;
IntRect oldRect(o->x(), o->y() , o->width(), o->height());
if (o->style()->clear() & CLEFT)
y = max(leftBottom(), y);
if (o->style()->clear() & CRIGHT)
y = max(rightBottom(), y);
if (o->style()->floating() == FLEFT) {
int heightRemainingLeft = 1;
int heightRemainingRight = 1;
int fx = leftRelOffset(y, lo, false, &heightRemainingLeft);
while (rightRelOffset(y, ro, false, &heightRemainingRight)-fx < fwidth) {
y += min(heightRemainingLeft, heightRemainingRight);
fx = leftRelOffset(y, lo, false, &heightRemainingLeft);
}
fx = max(0, fx);
f->m_left = fx;
o->setLocation(fx + o->marginLeft(), y + o->marginTop());
} else {
int heightRemainingLeft = 1;
int heightRemainingRight = 1;
int fx = rightRelOffset(y, ro, false, &heightRemainingRight);
while (fx - leftRelOffset(y, lo, false, &heightRemainingLeft) < fwidth) {
y += min(heightRemainingLeft, heightRemainingRight);
fx = rightRelOffset(y, ro, false, &heightRemainingRight);
}
f->m_left = fx - f->m_width;
o->setLocation(fx - o->marginRight() - o->width(), y + o->marginTop());
}
f->m_top = y;
f->m_bottom = f->m_top + _height;
if (o->checkForRepaintDuringLayout())
o->repaintDuringLayoutIfMoved(oldRect);
f = m_floatingObjects->next();
}
return true;
}
void RenderBlock::newLine(EClear clear)
{
positionNewFloats();
int newY = 0;
switch (clear)
{
case CLEFT:
newY = leftBottom();
break;
case CRIGHT:
newY = rightBottom();
break;
case CBOTH:
newY = floatBottom();
default:
break;
}
if (height() < newY)
setHeight(newY);
}
void RenderBlock::addPercentHeightDescendant(RenderBox* descendant)
{
if (!gPercentHeightDescendantsMap) {
gPercentHeightDescendantsMap = new PercentHeightDescendantsMap;
gPercentHeightContainerMap = new PercentHeightContainerMap;
}
HashSet<RenderBox*>* descendantSet = gPercentHeightDescendantsMap->get(this);
if (!descendantSet) {
descendantSet = new HashSet<RenderBox*>;
gPercentHeightDescendantsMap->set(this, descendantSet);
}
bool added = descendantSet->add(descendant).second;
if (!added) {
ASSERT(gPercentHeightContainerMap->get(descendant));
ASSERT(gPercentHeightContainerMap->get(descendant)->contains(this));
return;
}
HashSet<RenderBlock*>* containerSet = gPercentHeightContainerMap->get(descendant);
if (!containerSet) {
containerSet = new HashSet<RenderBlock*>;
gPercentHeightContainerMap->set(descendant, containerSet);
}
ASSERT(!containerSet->contains(this));
containerSet->add(this);
}
void RenderBlock::removePercentHeightDescendant(RenderBox* descendant)
{
if (!gPercentHeightContainerMap)
return;
HashSet<RenderBlock*>* containerSet = gPercentHeightContainerMap->take(descendant);
if (!containerSet)
return;
HashSet<RenderBlock*>::iterator end = containerSet->end();
for (HashSet<RenderBlock*>::iterator it = containerSet->begin(); it != end; ++it) {
RenderBlock* container = *it;
HashSet<RenderBox*>* descendantSet = gPercentHeightDescendantsMap->get(container);
ASSERT(descendantSet);
if (!descendantSet)
continue;
ASSERT(descendantSet->contains(descendant));
descendantSet->remove(descendant);
if (descendantSet->isEmpty()) {
gPercentHeightDescendantsMap->remove(container);
delete descendantSet;
}
}
delete containerSet;
}
HashSet<RenderBox*>* RenderBlock::percentHeightDescendants() const
{
return gPercentHeightDescendantsMap ? gPercentHeightDescendantsMap->get(this) : 0;
}
int RenderBlock::leftOffset() const
{
return borderLeft() + paddingLeft();
}
int RenderBlock::leftRelOffset(int y, int fixedOffset, bool applyTextIndent, int* heightRemaining) const
{
int left = fixedOffset;
if (m_floatingObjects) {
if ( heightRemaining ) *heightRemaining = 1;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it )
{
if (r->m_top <= y && r->m_bottom > y &&
r->type() == FloatingObject::FloatLeft &&
r->m_left + r->m_width > left) {
left = r->m_left + r->m_width;
if ( heightRemaining ) *heightRemaining = r->m_bottom - y;
}
}
}
if (applyTextIndent && style()->direction() == LTR) {
int cw = 0;
if (style()->textIndent().isPercent())
cw = containingBlock()->availableWidth();
left += style()->textIndent().calcMinValue(cw);
}
return left;
}
int RenderBlock::rightOffset() const
{
return borderLeft() + paddingLeft() + availableWidth();
}
int RenderBlock::rightRelOffset(int y, int fixedOffset, bool applyTextIndent, int* heightRemaining) const
{
int right = fixedOffset;
if (m_floatingObjects) {
if (heightRemaining) *heightRemaining = 1;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it )
{
if (r->m_top <= y && r->m_bottom > y &&
r->type() == FloatingObject::FloatRight &&
r->m_left < right) {
right = r->m_left;
if ( heightRemaining ) *heightRemaining = r->m_bottom - y;
}
}
}
if (applyTextIndent && style()->direction() == RTL) {
int cw = 0;
if (style()->textIndent().isPercent())
cw = containingBlock()->availableWidth();
right -= style()->textIndent().calcMinValue(cw);
}
return right;
}
int
RenderBlock::lineWidth(int y, bool firstLine) const
{
int result = rightOffset(y, firstLine) - leftOffset(y, firstLine);
return (result < 0) ? 0 : result;
}
int RenderBlock::nextFloatBottomBelow(int height) const
{
if (!m_floatingObjects)
return 0;
int bottom = INT_MAX;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it) {
if (r->m_bottom > height)
bottom = min(r->m_bottom, bottom);
}
return bottom == INT_MAX ? 0 : bottom;
}
int
RenderBlock::floatBottom() const
{
if (!m_floatingObjects) return 0;
int bottom = 0;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it )
if (r->m_bottom>bottom)
bottom = r->m_bottom;
return bottom;
}
int RenderBlock::lowestPosition(bool includeOverflowInterior, bool includeSelf) const
{
int bottom = includeSelf && width() > 0 ? height() : 0;
if (!includeOverflowInterior && (hasOverflowClip() || hasControlClip()))
return bottom;
if (!firstChild() && (!width() || !height()))
return bottom;
if (!hasColumns()) {
for (RenderObject* c = firstChild(); c; c = c->nextSibling()) {
if (!c->isFloatingOrPositioned() && c->isBox()) {
RenderBox* childBox = toRenderBox(c);
bottom = max(bottom, childBox->y() + childBox->lowestPosition(false));
}
}
}
if (includeSelf && isRelPositioned())
bottom += relativePositionOffsetY();
if (!includeOverflowInterior && hasOverflowClip())
return bottom;
int relativeOffset = includeSelf && isRelPositioned() ? relativePositionOffsetY() : 0;
if (includeSelf)
bottom = max(bottom, bottomLayoutOverflow() + relativeOffset);
if (m_positionedObjects) {
RenderBox* r;
Iterator end = m_positionedObjects->end();
for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
r = *it;
if (r->style()->position() != FixedPosition) {
if (!isRenderView() || r->x() + r->width() > 0 || r->x() + r->rightmostPosition(false) > 0) {
int lp = r->y() + r->lowestPosition(false);
bottom = max(bottom, lp + relativeOffset);
}
}
}
}
if (hasColumns()) {
Vector<IntRect>* colRects = columnRects();
for (unsigned i = 0; i < colRects->size(); i++)
bottom = max(bottom, colRects->at(i).bottom() + relativeOffset);
return bottom;
}
if (m_floatingObjects) {
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it ) {
if (r->m_shouldPaint || r->m_renderer->hasSelfPaintingLayer()) {
int lp = r->m_top + r->m_renderer->marginTop() + r->m_renderer->lowestPosition(false);
bottom = max(bottom, lp + relativeOffset);
}
}
}
if (!includeSelf) {
bottom = max(bottom, borderTop() + paddingTop() + paddingBottom() + relativeOffset);
if (childrenInline()) {
if (lastRootBox()) {
int childBottomEdge = lastRootBox()->selectionBottom();
bottom = max(bottom, childBottomEdge + paddingBottom() + relativeOffset);
}
} else {
RenderBox* currBox = lastChildBox();
while (currBox && currBox->isFloatingOrPositioned())
currBox = currBox->previousSiblingBox();
if (currBox) {
int childBottomEdge = currBox->y() + currBox->height() + currBox->collapsedMarginBottom();
bottom = max(bottom, childBottomEdge + paddingBottom() + relativeOffset);
}
}
}
return bottom;
}
int RenderBlock::rightmostPosition(bool includeOverflowInterior, bool includeSelf) const
{
int right = includeSelf && height() > 0 ? width() : 0;
if (!includeOverflowInterior && (hasOverflowClip() || hasControlClip()))
return right;
if (!firstChild() && (!width() || !height()))
return right;
if (!hasColumns()) {
for (RenderObject* c = firstChild(); c; c = c->nextSibling()) {
if (!c->isFloatingOrPositioned() && c->isBox()) {
RenderBox* childBox = toRenderBox(c);
right = max(right, childBox->x() + childBox->rightmostPosition(false));
}
}
}
if (includeSelf && isRelPositioned())
right += relativePositionOffsetX();
if (!includeOverflowInterior && hasOverflowClip())
return right;
int relativeOffset = includeSelf && isRelPositioned() ? relativePositionOffsetX() : 0;
if (includeSelf)
right = max(right, rightLayoutOverflow() + relativeOffset);
if (m_positionedObjects) {
RenderBox* r;
Iterator end = m_positionedObjects->end();
for (Iterator it = m_positionedObjects->begin() ; it != end; ++it) {
r = *it;
if (r->style()->position() != FixedPosition) {
if (!isRenderView() || r->y() + r->height() > 0 || r->y() + r->lowestPosition(false) > 0) {
int rp = r->x() + r->rightmostPosition(false);
right = max(right, rp + relativeOffset);
}
}
}
}
if (hasColumns()) {
if (style()->direction() == LTR)
right = max(columnRects()->last().right() + relativeOffset, right);
return right;
}
if (m_floatingObjects) {
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it ) {
if (r->m_shouldPaint || r->m_renderer->hasSelfPaintingLayer()) {
int rp = r->m_left + r->m_renderer->marginLeft() + r->m_renderer->rightmostPosition(false);
right = max(right, rp + relativeOffset);
}
}
}
if (!includeSelf) {
right = max(right, borderLeft() + paddingLeft() + paddingRight() + relativeOffset);
if (childrenInline()) {
for (InlineFlowBox* currBox = firstLineBox(); currBox; currBox = currBox->nextLineBox()) {
int childRightEdge = currBox->x() + currBox->width();
if (node() && node()->isContentEditable() && node() == node()->rootEditableElement() && style()->direction() == LTR && !paddingRight())
childRightEdge += 1;
right = max(right, childRightEdge + paddingRight() + relativeOffset);
}
} else {
for (RenderBox* currBox = firstChildBox(); currBox; currBox = currBox->nextSiblingBox()) {
if (currBox->isFloatingOrPositioned())
continue;
int childRightEdge = currBox->x() + currBox->width() + currBox->marginRight();
right = max(right, childRightEdge + paddingRight() + relativeOffset);
}
}
}
return right;
}
int RenderBlock::leftmostPosition(bool includeOverflowInterior, bool includeSelf) const
{
int left = includeSelf && height() > 0 ? 0 : width();
if (!includeOverflowInterior && (hasOverflowClip() || hasControlClip()))
return left;
if (!firstChild() && (!width() || !height()))
return left;
if (!hasColumns()) {
for (RenderObject* c = firstChild(); c; c = c->nextSibling()) {
if (!c->isFloatingOrPositioned() && c->isBox()) {
RenderBox* childBox = toRenderBox(c);
left = min(left, childBox->x() + childBox->leftmostPosition(false));
}
}
}
if (includeSelf && isRelPositioned())
left += relativePositionOffsetX();
if (!includeOverflowInterior && hasOverflowClip())
return left;
int relativeOffset = includeSelf && isRelPositioned() ? relativePositionOffsetX() : 0;
if (includeSelf)
left = min(left, leftLayoutOverflow() + relativeOffset);
if (m_positionedObjects) {
RenderBox* r;
Iterator end = m_positionedObjects->end();
for (Iterator it = m_positionedObjects->begin(); it != end; ++it) {
r = *it;
if (r->style()->position() != FixedPosition) {
if (!isRenderView() || r->y() + r->height() > 0 || r->y() + r->lowestPosition(false) > 0) {
int lp = r->x() + r->leftmostPosition(false);
left = min(left, lp + relativeOffset);
}
}
}
}
if (hasColumns()) {
if (style()->direction() == RTL)
left = min(columnRects()->last().x() + relativeOffset, left);
return left;
}
if (m_floatingObjects) {
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it ) {
if (r->m_shouldPaint || r->m_renderer->hasSelfPaintingLayer()) {
int lp = r->m_left + r->m_renderer->marginLeft() + r->m_renderer->leftmostPosition(false);
left = min(left, lp + relativeOffset);
}
}
}
if (!includeSelf && firstLineBox()) {
for (InlineFlowBox* currBox = firstLineBox(); currBox; currBox = currBox->nextLineBox())
left = min(left, (int)currBox->x() + relativeOffset);
}
return left;
}
int
RenderBlock::leftBottom()
{
if (!m_floatingObjects) return 0;
int bottom = 0;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it )
if (r->m_bottom > bottom && r->type() == FloatingObject::FloatLeft)
bottom = r->m_bottom;
return bottom;
}
int
RenderBlock::rightBottom()
{
if (!m_floatingObjects) return 0;
int bottom = 0;
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for ( ; (r = it.current()); ++it )
if (r->m_bottom>bottom && r->type() == FloatingObject::FloatRight)
bottom = r->m_bottom;
return bottom;
}
void RenderBlock::markLinesDirtyInVerticalRange(int top, int bottom, RootInlineBox* highest)
{
if (top >= bottom)
return;
RootInlineBox* lowestDirtyLine = lastRootBox();
RootInlineBox* afterLowest = lowestDirtyLine;
while (lowestDirtyLine && lowestDirtyLine->blockHeight() >= bottom) {
afterLowest = lowestDirtyLine;
lowestDirtyLine = lowestDirtyLine->prevRootBox();
}
while (afterLowest && afterLowest != highest && afterLowest->blockHeight() >= top) {
afterLowest->markDirty();
afterLowest = afterLowest->prevRootBox();
}
}
void RenderBlock::clearFloats()
{
if (avoidsFloats() || isRoot() || isRenderView() || isFloatingOrPositioned() || isTableCell()) {
if (m_floatingObjects)
m_floatingObjects->clear();
return;
}
typedef HashMap<RenderObject*, FloatingObject*> RendererToFloatInfoMap;
RendererToFloatInfoMap floatMap;
if (m_floatingObjects) {
if (childrenInline()) {
m_floatingObjects->first();
while (FloatingObject* f = m_floatingObjects->take())
floatMap.add(f->m_renderer, f);
} else
m_floatingObjects->clear();
}
if (!parent() || !parent()->isRenderBlock())
return;
bool parentHasFloats = false;
RenderObject* prev = previousSibling();
while (prev && (prev->isFloatingOrPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
if (prev->isFloating())
parentHasFloats = true;
prev = prev->previousSibling();
}
int offset = y();
if (parentHasFloats) {
RenderBlock* parentBlock = toRenderBlock(parent());
addIntrudingFloats(parentBlock, parentBlock->borderLeft() + parentBlock->paddingLeft(), offset);
}
int xoffset = 0;
if (prev)
offset -= toRenderBox(prev)->y();
else if (parent()->isBox()) {
prev = parent();
xoffset += toRenderBox(prev)->borderLeft() + toRenderBox(prev)->paddingLeft();
}
if (!prev || !prev->isRenderBlock())
return;
RenderBlock* block = toRenderBlock(prev);
if (block->m_floatingObjects && block->floatBottom() > offset)
addIntrudingFloats(block, xoffset, offset);
if (childrenInline()) {
int changeTop = numeric_limits<int>::max();
int changeBottom = numeric_limits<int>::min();
if (m_floatingObjects) {
for (FloatingObject* f = m_floatingObjects->first(); f; f = m_floatingObjects->next()) {
FloatingObject* oldFloatingObject = floatMap.get(f->m_renderer);
if (oldFloatingObject) {
if (f->m_width != oldFloatingObject->m_width || f->m_left != oldFloatingObject->m_left) {
changeTop = 0;
changeBottom = max(changeBottom, max(f->m_bottom, oldFloatingObject->m_bottom));
} else if (f->m_bottom != oldFloatingObject->m_bottom) {
changeTop = min(changeTop, min(f->m_bottom, oldFloatingObject->m_bottom));
changeBottom = max(changeBottom, max(f->m_bottom, oldFloatingObject->m_bottom));
}
floatMap.remove(f->m_renderer);
delete oldFloatingObject;
} else {
changeTop = 0;
changeBottom = max(changeBottom, f->m_bottom);
}
}
}
RendererToFloatInfoMap::iterator end = floatMap.end();
for (RendererToFloatInfoMap::iterator it = floatMap.begin(); it != end; ++it) {
FloatingObject* floatingObject = (*it).second;
if (!floatingObject->m_isDescendant) {
changeTop = 0;
changeBottom = max(changeBottom, floatingObject->m_bottom);
}
}
deleteAllValues(floatMap);
markLinesDirtyInVerticalRange(changeTop, changeBottom);
}
}
int RenderBlock::addOverhangingFloats(RenderBlock* child, int xoff, int yoff, bool makeChildPaintOtherFloats)
{
if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot())
return 0;
int lowestFloatBottom = 0;
DeprecatedPtrListIterator<FloatingObject> it(*child->m_floatingObjects);
for (FloatingObject* r; (r = it.current()); ++it) {
int bottom = child->y() + r->m_bottom;
lowestFloatBottom = max(lowestFloatBottom, bottom);
if (bottom > height()) {
if (!containsFloat(r->m_renderer)) {
FloatingObject *floatingObj = new FloatingObject(r->type());
floatingObj->m_top = r->m_top - yoff;
floatingObj->m_bottom = r->m_bottom - yoff;
floatingObj->m_left = r->m_left - xoff;
floatingObj->m_width = r->m_width;
floatingObj->m_renderer = r->m_renderer;
if (r->m_renderer->enclosingSelfPaintingLayer() == enclosingSelfPaintingLayer())
r->m_shouldPaint = false;
else
floatingObj->m_shouldPaint = false;
if (!m_floatingObjects) {
m_floatingObjects = new DeprecatedPtrList<FloatingObject>;
m_floatingObjects->setAutoDelete(true);
}
m_floatingObjects->append(floatingObj);
}
} else if (makeChildPaintOtherFloats && !r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer() &&
r->m_renderer->isDescendantOf(child) && r->m_renderer->enclosingLayer() == child->enclosingLayer())
r->m_shouldPaint = true;
if (r->m_shouldPaint && !r->m_renderer->hasSelfPaintingLayer())
child->addOverflowFromChild(r->m_renderer, IntSize(r->m_left + r->m_renderer->marginLeft(), r->m_top + r->m_renderer->marginTop()));
}
return lowestFloatBottom;
}
void RenderBlock::addIntrudingFloats(RenderBlock* prev, int xoff, int yoff)
{
if (!prev->m_floatingObjects)
return;
DeprecatedPtrListIterator<FloatingObject> it(*prev->m_floatingObjects);
for (FloatingObject *r; (r = it.current()); ++it) {
if (r->m_bottom > yoff) {
FloatingObject* f = 0;
if (m_floatingObjects) {
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
while ((f = it.current())) {
if (f->m_renderer == r->m_renderer) break;
++it;
}
}
if (!f) {
FloatingObject *floatingObj = new FloatingObject(r->type());
floatingObj->m_top = r->m_top - yoff;
floatingObj->m_bottom = r->m_bottom - yoff;
floatingObj->m_left = r->m_left - xoff;
if (prev != parent())
floatingObj->m_left += prev->marginLeft();
floatingObj->m_left -= marginLeft();
floatingObj->m_shouldPaint = false; floatingObj->m_width = r->m_width;
floatingObj->m_renderer = r->m_renderer;
if (!m_floatingObjects) {
m_floatingObjects = new DeprecatedPtrList<FloatingObject>;
m_floatingObjects->setAutoDelete(true);
}
m_floatingObjects->append(floatingObj);
}
}
}
}
bool RenderBlock::avoidsFloats() const
{
return RenderBox::avoidsFloats() || !style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth();
}
bool RenderBlock::containsFloat(RenderObject* o)
{
if (m_floatingObjects) {
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
while (it.current()) {
if (it.current()->m_renderer == o)
return true;
++it;
}
}
return false;
}
void RenderBlock::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
{
setChildNeedsLayout(true, !inLayout);
if (floatToRemove)
removeFloatingObject(floatToRemove);
if (!childrenInline()) {
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if ((!floatToRemove && child->isFloatingOrPositioned()) || !child->isRenderBlock())
continue;
RenderBlock* childBlock = toRenderBlock(child);
if ((floatToRemove ? childBlock->containsFloat(floatToRemove) : childBlock->containsFloats()) || childBlock->shrinkToAvoidFloats())
childBlock->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
}
}
}
int RenderBlock::visibleTopOfHighestFloatExtendingBelow(int bottom, int maxHeight) const
{
int top = bottom;
if (m_floatingObjects) {
FloatingObject* floatingObject;
for (DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects); (floatingObject = it.current()); ++it) {
RenderBox* floatingBox = floatingObject->m_renderer;
IntRect visibleOverflow = floatingBox->visibleOverflowRect();
visibleOverflow.move(floatingBox->x(), floatingBox->y());
if (visibleOverflow.y() < top && visibleOverflow.bottom() > bottom && visibleOverflow.height() <= maxHeight && floatingBox->containingBlock() == this)
top = visibleOverflow.y();
}
}
if (!childrenInline()) {
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isFloatingOrPositioned() || !child->isRenderBlock())
continue;
RenderBlock* childBlock = toRenderBlock(child);
top = min(top, childBlock->y() + childBlock->visibleTopOfHighestFloatExtendingBelow(bottom - childBlock->y(), maxHeight));
}
}
return top;
}
int RenderBlock::getClearDelta(RenderBox* child, int yPos)
{
if (!containsFloats())
return 0;
bool clearSet = child->style()->clear() != CNONE;
int bottom = 0;
switch (child->style()->clear()) {
case CNONE:
break;
case CLEFT:
bottom = leftBottom();
break;
case CRIGHT:
bottom = rightBottom();
break;
case CBOTH:
bottom = floatBottom();
break;
}
int result = clearSet ? max(0, bottom - yPos) : 0;
if (!result && child->avoidsFloats()) {
int availableWidth = this->availableWidth();
if (child->minPrefWidth() > availableWidth)
return 0;
int y = yPos;
while (true) {
int widthAtY = lineWidth(y, false);
if (widthAtY == availableWidth)
return y - yPos;
int oldChildY = child->y();
int oldChildWidth = child->width();
child->setY(y);
child->calcWidth();
int childWidthAtY = child->width();
child->setY(oldChildY);
child->setWidth(oldChildWidth);
if (childWidthAtY <= widthAtY)
return y - yPos;
y = nextFloatBottomBelow(y);
ASSERT(y >= yPos);
if (y < yPos)
break;
}
ASSERT_NOT_REACHED();
}
return result;
}
bool RenderBlock::isPointInOverflowControl(HitTestResult& result, int _x, int _y, int _tx, int _ty)
{
if (!scrollsOverflow())
return false;
return layer()->hitTestOverflowControls(result, IntPoint(_x - _tx, _y - _ty));
}
bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, int _x, int _y, int _tx, int _ty, HitTestAction hitTestAction)
{
int tx = _tx + x();
int ty = _ty + y();
if (!isRenderView()) {
IntRect overflowBox = visibleOverflowRect();
overflowBox.move(tx, ty);
if (!overflowBox.contains(_x, _y))
return false;
}
if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && isPointInOverflowControl(result, _x, _y, tx, ty)) {
updateHitTestResult(result, IntPoint(_x - tx, _y - ty));
return true;
}
bool useOverflowClip = hasOverflowClip() && !hasSelfPaintingLayer();
bool useClip = (hasControlClip() || useOverflowClip);
bool checkChildren = !useClip || (hasControlClip() ? controlClipRect(tx, ty).contains(_x, _y) : overflowClipRect(tx, ty).contains(_x, _y));
if (checkChildren) {
int scrolledX = tx;
int scrolledY = ty;
if (hasOverflowClip()) {
IntSize offset = layer()->scrolledContentOffset();
scrolledX -= offset.width();
scrolledY -= offset.height();
}
if (!hasColumns()) {
if (hitTestContents(request, result, _x, _y, scrolledX, scrolledY, hitTestAction)) {
updateHitTestResult(result, IntPoint(_x - tx, _y - ty));
return true;
}
if (hitTestAction == HitTestFloat && hitTestFloats(request, result, _x, _y, scrolledX, scrolledY))
return true;
} else if (hitTestColumns(request, result, _x, _y, scrolledX, scrolledY, hitTestAction)) {
updateHitTestResult(result, IntPoint(_x - tx, _y - ty));
return true;
}
}
if (hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) {
IntRect boundsRect(tx, ty, width(), height());
if (visibleToHitTesting() && boundsRect.contains(_x, _y)) {
updateHitTestResult(result, IntPoint(_x - tx, _y - ty));
return true;
}
}
return false;
}
bool RenderBlock::hitTestFloats(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty)
{
if (!m_floatingObjects)
return false;
if (isRenderView()) {
tx += toRenderView(this)->frameView()->scrollX();
ty += toRenderView(this)->frameView()->scrollY();
}
FloatingObject* floatingObject;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for (it.toLast(); (floatingObject = it.current()); --it) {
if (floatingObject->m_shouldPaint && !floatingObject->m_renderer->hasSelfPaintingLayer()) {
int xOffset = tx + floatingObject->m_left + floatingObject->m_renderer->marginLeft() - floatingObject->m_renderer->x();
int yOffset = ty + floatingObject->m_top + floatingObject->m_renderer->marginTop() - floatingObject->m_renderer->y();
if (floatingObject->m_renderer->hitTest(request, result, IntPoint(x, y), xOffset, yOffset)) {
updateHitTestResult(result, IntPoint(x - xOffset, y - yOffset));
return true;
}
}
}
return false;
}
bool RenderBlock::hitTestColumns(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty, HitTestAction hitTestAction)
{
int currXOffset = 0;
int currYOffset = 0;
int colGap = columnGap();
Vector<IntRect>* colRects = columnRects();
for (unsigned i = 0; i < colRects->size(); i++) {
IntRect colRect = colRects->at(i);
colRect.move(tx, ty);
if (colRect.contains(x, y)) {
int finalX = tx + currXOffset;
int finalY = ty + currYOffset;
return hitTestContents(request, result, x, y, finalX, finalY, hitTestAction) || hitTestAction == HitTestFloat && hitTestFloats(request, result, x, y, finalX, finalY);
}
if (style()->direction() == LTR)
currXOffset += colRect.width() + colGap;
else
currXOffset -= (colRect.width() + colGap);
currYOffset -= colRect.height();
}
return false;
}
bool RenderBlock::hitTestContents(const HitTestRequest& request, HitTestResult& result, int x, int y, int tx, int ty, HitTestAction hitTestAction)
{
if (childrenInline() && !isTable()) {
if (m_lineBoxes.hitTest(this, request, result, x, y, tx, ty, hitTestAction)) {
updateHitTestResult(result, IntPoint(x - tx, y - ty));
return true;
}
} else {
HitTestAction childHitTest = hitTestAction;
if (hitTestAction == HitTestChildBlockBackgrounds)
childHitTest = HitTestChildBlockBackground;
for (RenderBox* child = lastChildBox(); child; child = child->previousSiblingBox()) {
if (!child->hasSelfPaintingLayer() && !child->isFloating() && child->nodeAtPoint(request, result, x, y, tx, ty, childHitTest)) {
updateHitTestResult(result, IntPoint(x - tx, y - ty));
return true;
}
}
}
return false;
}
Position RenderBlock::positionForBox(InlineBox *box, bool start) const
{
if (!box)
return Position();
if (!box->renderer()->node())
return Position(node(), start ? caretMinOffset() : caretMaxOffset());
if (!box->isInlineTextBox())
return Position(box->renderer()->node(), start ? box->renderer()->caretMinOffset() : box->renderer()->caretMaxOffset());
InlineTextBox *textBox = static_cast<InlineTextBox *>(box);
return Position(box->renderer()->node(), start ? textBox->start() : textBox->start() + textBox->len());
}
Position RenderBlock::positionForRenderer(RenderObject* renderer, bool start) const
{
if (!renderer)
return Position(node(), 0);
Node* n = renderer->node() ? renderer->node() : node();
if (!n)
return Position();
ASSERT(renderer == n->renderer());
int offset = start ? renderer->caretMinOffset() : renderer->caretMaxOffset();
ASSERT(!n->isCharacterDataNode() || renderer->isText());
return Position(n, offset);
}
static VisiblePosition positionForPointRespectingEditingBoundaries(RenderBox* parent, RenderBox* child, const IntPoint& pointInParentCoordinates)
{
IntPoint pointInChildCoordinates(pointInParentCoordinates - child->location());
Node* childNode = child->node();
if (!childNode)
return child->positionForPoint(pointInChildCoordinates);
RenderObject* ancestor = parent;
while (ancestor && !ancestor->node())
ancestor = ancestor->parent();
if (!ancestor || ancestor->node()->isContentEditable() == childNode->isContentEditable())
return child->positionForPoint(pointInChildCoordinates);
if (childNode->isContentEditable() && !ancestor->node()->isContentEditable())
return child->positionForPoint(pointInChildCoordinates);
int childMidX = child->width() / 2;
if (pointInChildCoordinates.x() < childMidX)
return ancestor->createVisiblePosition(childNode->nodeIndex(), DOWNSTREAM);
return ancestor->createVisiblePosition(childNode->nodeIndex() + 1, UPSTREAM);
}
VisiblePosition RenderBlock::positionForPointWithInlineChildren(const IntPoint& pointInContents)
{
ASSERT(childrenInline());
if (!firstRootBox())
return createVisiblePosition(0, DOWNSTREAM);
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;
lastRootBoxWithChildren = root;
int bottom;
if (root->nextRootBox()) {
bottom = root->nextRootBox()->lineTop();
} else
bottom = root->lineBottom() + verticalLineClickFudgeFactor;
if (pointInContents.y() < bottom) {
closestBox = root->closestLeafChildForXPos(pointInContents.x());
if (closestBox)
break;
}
}
Settings* settings = document()->settings();
bool useWindowsBehavior = settings && settings->editingBehavior() == EditingWindowsBehavior;
useWindowsBehavior = document()->frame()->singleLineSelectionBehavior();
if (useWindowsBehavior && !closestBox && lastRootBoxWithChildren) {
closestBox = lastRootBoxWithChildren->closestLeafChildForXPos(pointInContents.x());
}
if (closestBox) {
if (!useWindowsBehavior && pointInContents.y() < firstRootBoxWithChildren->lineTop() - verticalLineClickFudgeFactor) {
return VisiblePosition(positionForBox(firstRootBoxWithChildren->firstLeafChild(), true), DOWNSTREAM);
}
return closestBox->renderer()->positionForPoint(IntPoint(pointInContents.x(), closestBox->m_y));
}
if (lastRootBoxWithChildren) {
ASSERT(!useWindowsBehavior);
return VisiblePosition(positionForBox(lastRootBoxWithChildren->lastLeafChild(), false), DOWNSTREAM);
}
return createVisiblePosition(0, DOWNSTREAM);
}
static inline bool isChildHitTestCandidate(RenderBox* box)
{
return box->height() && box->style()->visibility() == VISIBLE && !box->isFloatingOrPositioned();
}
VisiblePosition RenderBlock::positionForPoint(const IntPoint& point)
{
if (isTable())
return RenderBox::positionForPoint(point);
if (isReplaced()) {
if (point.y() < 0 || (point.y() < height() && point.x() < 0))
return createVisiblePosition(caretMinOffset(), DOWNSTREAM);
if (point.y() >= height() || (point.y() >= 0 && point.x() >= width()))
return createVisiblePosition(caretMaxOffset(), DOWNSTREAM);
}
int contentsX = point.x();
int contentsY = point.y();
offsetForContents(contentsX, contentsY);
IntPoint pointInContents(contentsX, contentsY);
if (childrenInline())
return positionForPointWithInlineChildren(pointInContents);
if (lastChildBox() && contentsY > lastChildBox()->y()) {
for (RenderBox* childBox = lastChildBox(); childBox; childBox = childBox->previousSiblingBox()) {
if (isChildHitTestCandidate(childBox))
return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
}
} else {
for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
if (isChildHitTestCandidate(childBox) && contentsY < childBox->frameRect().bottom())
return positionForPointRespectingEditingBoundaries(this, childBox, pointInContents);
}
}
return RenderBox::positionForPoint(point);
}
void RenderBlock::offsetForContents(int& tx, int& ty) const
{
IntPoint contentsPoint(tx, ty);
if (hasOverflowClip())
contentsPoint += layer()->scrolledContentOffset();
if (hasColumns())
adjustPointToColumnContents(contentsPoint);
tx = contentsPoint.x();
ty = contentsPoint.y();
}
int RenderBlock::availableWidth() const
{
if (hasColumns())
return desiredColumnWidth();
return contentWidth();
}
int RenderBlock::columnGap() const
{
if (style()->hasNormalColumnGap())
return style()->fontDescription().computedPixelSize(); return static_cast<int>(style()->columnGap());
}
void RenderBlock::calcColumnWidth()
{
unsigned desiredColumnCount = 1;
int desiredColumnWidth = contentWidth();
if (document()->printing() || (style()->hasAutoColumnCount() && style()->hasAutoColumnWidth())) {
setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
return;
}
int availWidth = desiredColumnWidth;
int colGap = columnGap();
int colWidth = max(1, static_cast<int>(style()->columnWidth()));
int colCount = max(1, static_cast<int>(style()->columnCount()));
if (style()->hasAutoColumnWidth()) {
if ((colCount - 1) * colGap < availWidth) {
desiredColumnCount = colCount;
desiredColumnWidth = (availWidth - (desiredColumnCount - 1) * colGap) / desiredColumnCount;
} else if (colGap < availWidth) {
desiredColumnCount = availWidth / colGap;
if (desiredColumnCount < 1)
desiredColumnCount = 1;
desiredColumnWidth = (availWidth - (desiredColumnCount - 1) * colGap) / desiredColumnCount;
}
} else if (style()->hasAutoColumnCount()) {
if (colWidth < availWidth) {
desiredColumnCount = (availWidth + colGap) / (colWidth + colGap);
if (desiredColumnCount < 1)
desiredColumnCount = 1;
desiredColumnWidth = (availWidth - (desiredColumnCount - 1) * colGap) / desiredColumnCount;
}
} else {
if (colCount * colWidth + (colCount - 1) * colGap <= availWidth) {
desiredColumnCount = colCount;
desiredColumnWidth = colWidth;
} else if (colWidth < availWidth) {
desiredColumnCount = (availWidth + colGap) / (colWidth + colGap);
if (desiredColumnCount < 1)
desiredColumnCount = 1;
desiredColumnWidth = (availWidth - (desiredColumnCount - 1) * colGap) / desiredColumnCount;
}
}
setDesiredColumnCountAndWidth(desiredColumnCount, desiredColumnWidth);
}
void RenderBlock::setDesiredColumnCountAndWidth(int count, int width)
{
if (count == 1 && style()->hasAutoColumnWidth()) {
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->m_desiredColumnCount = count;
info->m_desiredColumnWidth = width;
}
}
int RenderBlock::desiredColumnWidth() const
{
if (!hasColumns())
return contentWidth();
return gColumnInfoMap->get(this)->m_desiredColumnWidth;
}
unsigned RenderBlock::desiredColumnCount() const
{
if (!hasColumns())
return 1;
return gColumnInfoMap->get(this)->m_desiredColumnCount;
}
Vector<IntRect>* RenderBlock::columnRects() const
{
if (!hasColumns())
return 0;
return &gColumnInfoMap->get(this)->m_columnRects;
}
int RenderBlock::layoutColumns(int endOfContent, int requestedColumnHeight)
{
if (!hasColumns())
return -1;
ColumnInfo* info = gColumnInfoMap->get(this);
int desiredColumnWidth = info->m_desiredColumnWidth;
int desiredColumnCount = info->m_desiredColumnCount;
Vector<IntRect>* columnRects = &info->m_columnRects;
bool computeIntrinsicHeight = (endOfContent == -1);
int columnSlop = lineHeight(false) / 2;
int remainingSlopSpace = columnSlop * desiredColumnCount;
int availableHeight = contentHeight();
int colHeight;
if (computeIntrinsicHeight && requestedColumnHeight >= 0)
colHeight = requestedColumnHeight;
else if (computeIntrinsicHeight)
colHeight = availableHeight / desiredColumnCount + columnSlop;
else
colHeight = availableHeight;
int originalColHeight = colHeight;
int colGap = columnGap();
columnRects->clear();
RenderView* v = view();
int left = borderLeft() + paddingLeft();
int top = borderTop() + paddingTop();
int currX = style()->direction() == LTR ? borderLeft() + paddingLeft() : borderLeft() + paddingLeft() + contentWidth() - desiredColumnWidth;
int currY = top;
unsigned colCount = desiredColumnCount;
int maxColBottom = borderTop() + paddingTop();
int contentBottom = top + availableHeight;
int minimumColumnHeight = -1;
for (unsigned i = 0; i < colCount; i++) {
if (computeIntrinsicHeight && i == colCount - 1)
colHeight = availableHeight;
IntRect colRect(currX, top, desiredColumnWidth, colHeight);
int truncationPoint = visibleTopOfHighestFloatExtendingBelow(currY + colHeight, colHeight);
IntRect pageRect(left, currY, contentWidth(), truncationPoint - currY);
v->setPrintRect(pageRect);
v->setTruncatedAt(truncationPoint);
GraphicsContext context((PlatformGraphicsContext*)0);
RenderObject::PaintInfo paintInfo(&context, pageRect, PaintPhaseForeground, false, 0, 0);
setHasColumns(false);
paintObject(paintInfo, 0, 0);
setHasColumns(true);
if (computeIntrinsicHeight && v->minimumColumnHeight() > originalColHeight) {
minimumColumnHeight = max(minimumColumnHeight, v->minimumColumnHeight());
}
int adjustedBottom = v->bestTruncatedAt();
if (adjustedBottom <= currY)
adjustedBottom = truncationPoint;
colRect.setHeight(adjustedBottom - currY);
if (computeIntrinsicHeight) {
int lostSpace = colHeight - colRect.height();
if (lostSpace > remainingSlopSpace) {
int spaceToRedistribute = lostSpace - remainingSlopSpace;
int remainingColumns = colCount - i + 1;
colHeight += spaceToRedistribute / remainingColumns;
}
remainingSlopSpace = max(0, remainingSlopSpace - lostSpace);
}
if (style()->direction() == LTR)
currX += desiredColumnWidth + colGap;
else
currX -= (desiredColumnWidth + colGap);
currY += colRect.height();
availableHeight -= colRect.height();
maxColBottom = max(colRect.bottom(), maxColBottom);
columnRects->append(colRect);
if (currY < endOfContent && i == colCount - 1 && (computeIntrinsicHeight || contentHeight()))
colCount++;
}
if (minimumColumnHeight >= 0) {
return layoutColumns(endOfContent, minimumColumnHeight);
}
int overflowRight = max(width(), currX - colGap);
int overflowLeft = min(0, currX + desiredColumnWidth + colGap);
int overflowHeight = maxColBottom;
int toAdd = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
if (computeIntrinsicHeight)
setHeight(maxColBottom + toAdd);
m_overflow.clear();
addLayoutOverflow(IntRect(overflowLeft, 0, overflowRight - overflowLeft, overflowHeight));
v->setPrintRect(IntRect());
v->setTruncatedAt(0);
ASSERT(colCount == columnRects->size());
return contentBottom;
}
void RenderBlock::adjustPointToColumnContents(IntPoint& point) const
{
if (!hasColumns())
return;
Vector<IntRect>* colRects = columnRects();
int colGap = columnGap();
int leftGap = colGap / 2;
IntPoint columnPoint(colRects->at(0).location());
int yOffset = 0;
for (unsigned i = 0; i < colRects->size(); i++) {
IntRect colRect = colRects->at(i);
IntRect gapAndColumnRect(colRect.x() - leftGap, colRect.y(), colRect.width() + colGap, colRect.height());
if (point.x() >= gapAndColumnRect.x() && point.x() < gapAndColumnRect.right()) {
if (point.y() < gapAndColumnRect.y())
point = gapAndColumnRect.location();
else if (point.y() >= gapAndColumnRect.bottom()) {
point = gapAndColumnRect.location();
point.move(0, gapAndColumnRect.height());
}
point.move(columnPoint.x() - colRect.x(), yOffset);
return;
}
yOffset += colRect.height();
}
}
void RenderBlock::adjustRectForColumns(IntRect& r) const
{
if (!hasColumns())
return;
Vector<IntRect>* colRects = columnRects();
IntRect result;
int currXOffset = 0;
int currYOffset = 0;
int colGap = columnGap();
for (unsigned i = 0; i < colRects->size(); i++) {
IntRect colRect = colRects->at(i);
IntRect repaintRect = r;
repaintRect.move(currXOffset, currYOffset);
repaintRect.intersect(colRect);
result.unite(repaintRect);
if (style()->direction() == LTR)
currXOffset += colRect.width() + colGap;
else
currXOffset -= (colRect.width() + colGap);
currYOffset -= colRect.height();
}
r = result;
}
void RenderBlock::adjustForColumns(IntSize& offset, const IntPoint& point) const
{
if (!hasColumns())
return;
Vector<IntRect>& columnRects = *this->columnRects();
int gapWidth = columnGap();
int xOffset = 0;
int yOffset = 0;
size_t columnCount = columnRects.size();
for (size_t i = 0; i < columnCount; ++i) {
IntRect columnRect = columnRects[i];
if (point.y() < columnRect.bottom() + yOffset) {
offset.expand(xOffset, -yOffset);
return;
}
if (style()->direction() == LTR)
xOffset += columnRect.width() + gapWidth;
else
xOffset -= columnRect.width() + gapWidth;
yOffset += columnRect.height();
}
}
void RenderBlock::calcPrefWidths()
{
ASSERT(prefWidthsDirty());
updateFirstLetter();
if (!isTableCell() && style()->width().isFixed() && style()->width().value() > 0)
m_minPrefWidth = m_maxPrefWidth = calcContentBoxWidth(style()->width().value());
else {
m_minPrefWidth = 0;
m_maxPrefWidth = 0;
if (childrenInline())
calcInlinePrefWidths();
else
calcBlockPrefWidths();
m_maxPrefWidth = max(m_minPrefWidth, m_maxPrefWidth);
if (!style()->autoWrap() && childrenInline()) {
m_minPrefWidth = m_maxPrefWidth;
if (layer() && layer()->marquee() && layer()->marquee()->isHorizontal())
m_minPrefWidth = 0;
}
if (isTableCell()) {
Length w = toRenderTableCell(this)->styleOrColWidth();
if (w.isFixed() && w.value() > 0)
m_maxPrefWidth = max(m_minPrefWidth, calcContentBoxWidth(w.value()));
}
}
if (style()->minWidth().isFixed() && style()->minWidth().value() > 0) {
m_maxPrefWidth = max(m_maxPrefWidth, calcContentBoxWidth(style()->minWidth().value()));
m_minPrefWidth = max(m_minPrefWidth, calcContentBoxWidth(style()->minWidth().value()));
}
if (style()->maxWidth().isFixed() && style()->maxWidth().value() != undefinedLength) {
m_maxPrefWidth = min(m_maxPrefWidth, calcContentBoxWidth(style()->maxWidth().value()));
m_minPrefWidth = min(m_minPrefWidth, calcContentBoxWidth(style()->maxWidth().value()));
}
int toAdd = 0;
toAdd = borderAndPaddingWidth();
if (hasOverflowClip() && style()->overflowY() == OSCROLL)
toAdd += verticalScrollbarWidth();
m_minPrefWidth += toAdd;
m_maxPrefWidth += toAdd;
setPrefWidthsDirty(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->isPositioned())))
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->isPositioned() && (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* cstyle = child->style();
int result = 0;
bool leftSide = (cstyle->direction() == LTR) ? !endOfInline : endOfInline;
result += getBPMWidth((leftSide ? child->marginLeft() : child->marginRight()),
(leftSide ? cstyle->marginLeft() :
cstyle->marginRight()));
result += getBPMWidth((leftSide ? child->paddingLeft() : child->paddingRight()),
(leftSide ? cstyle->paddingLeft() :
cstyle->paddingRight()));
result += leftSide ? child->borderLeft() : child->borderRight();
return result;
}
static inline void stripTrailingSpace(int& inlineMax, int& inlineMin,
RenderObject* trailingSpaceChild)
{
if (trailingSpaceChild && trailingSpaceChild->isText()) {
RenderText* t = toRenderText(trailingSpaceChild);
const UChar space = ' ';
const Font& font = t->style()->font(); int spaceWidth = font.width(TextRun(&space, 1));
inlineMax -= spaceWidth + font.wordSpacing();
if (inlineMin > inlineMax)
inlineMin = inlineMax;
}
}
void RenderBlock::calcInlinePrefWidths()
{
int inlineMax = 0;
int inlineMin = 0;
int cw = containingBlock()->contentWidth();
bool stripFrontSpaces = true;
RenderObject* trailingSpaceChild = 0;
bool allowImagesToBreak = !style()->htmlHacks() || !isTableCell() || !style()->width().isIntrinsicOrAuto();
bool autoWrap, oldAutoWrap;
autoWrap = oldAutoWrap = style()->autoWrap();
InlineMinMaxIterator childIterator(this);
bool addedTextIndent = false; RenderObject* prevFloat = 0;
RenderObject* previousLeaf = 0;
while (RenderObject* child = childIterator.next()) {
autoWrap = child->isReplaced() ? child->parent()->style()->autoWrap() :
child->style()->autoWrap();
if (!child->isBR()) {
RenderStyle* cstyle = child->style();
int childMin = 0;
int childMax = 0;
if (!child->isText()) {
if (child->isRenderInline()) {
int bpm = getBorderPaddingMargin(toRenderInline(child), childIterator.endOfInline);
childMin += bpm;
childMax += bpm;
inlineMin += childMin;
inlineMax += childMax;
child->setPrefWidthsDirty(false);
} else {
int margins = 0;
Length leftMargin = cstyle->marginLeft();
Length rightMargin = cstyle->marginRight();
if (leftMargin.isFixed())
margins += leftMargin.value();
if (rightMargin.isFixed())
margins += rightMargin.value();
childMin += margins;
childMax += margins;
}
}
if (!child->isRenderInline() && !child->isText()) {
childMin += child->minPrefWidth();
childMax += child->maxPrefWidth();
bool clearPreviousFloat;
if (child->isFloating()) {
clearPreviousFloat = (prevFloat
&& ((prevFloat->style()->floating() == FLEFT && (child->style()->clear() & CLEFT))
|| (prevFloat->style()->floating() == FRIGHT && (child->style()->clear() & CRIGHT))));
prevFloat = child;
} else
clearPreviousFloat = false;
bool canBreakReplacedElement = !child->isImage() || allowImagesToBreak;
if ((canBreakReplacedElement && (autoWrap || oldAutoWrap)) || clearPreviousFloat) {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
inlineMin = 0;
}
if (clearPreviousFloat) {
m_maxPrefWidth = max(inlineMax, m_maxPrefWidth);
inlineMax = 0;
}
int ti = 0;
if (!addedTextIndent) {
addedTextIndent = true;
ti = style()->textIndent().calcMinValue(cw);
childMin+=ti;
childMax+=ti;
}
inlineMax += childMax;
if (!autoWrap || !canBreakReplacedElement) {
if (child->isFloating())
m_minPrefWidth = max(childMin, m_minPrefWidth);
else
inlineMin += childMin;
} else {
m_minPrefWidth = max(childMin, m_minPrefWidth);
inlineMin = 0;
}
if (!child->isFloating()) {
stripFrontSpaces = false;
trailingSpaceChild = 0;
}
} else if (child->isText()) {
RenderText* t = toRenderText(child);
if (t->isWordBreak()) {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
inlineMin = 0;
continue;
}
bool hasBreakableChar, hasBreak;
int beginMin, endMin;
bool beginWS, endWS;
int beginMax, endMax;
t->trimmedPrefWidths(inlineMax, beginMin, beginWS, endMin, endWS,
hasBreakableChar, hasBreak, beginMax, endMax,
childMin, childMax, stripFrontSpaces);
if (!hasBreak && childMax == 0) {
if (autoWrap && (beginWS || endWS)) {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
inlineMin = 0;
}
continue;
}
if (stripFrontSpaces)
trailingSpaceChild = child;
else
trailingSpaceChild = 0;
int ti = 0;
if (!addedTextIndent) {
addedTextIndent = true;
ti = style()->textIndent().calcMinValue(cw);
childMin+=ti; beginMin += ti;
childMax+=ti; beginMax += ti;
}
if (!hasBreakableChar) {
inlineMin += childMin;
} else {
if (beginWS)
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
else {
inlineMin += beginMin;
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
childMin -= ti;
}
inlineMin = childMin;
if (endWS) {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
inlineMin = 0;
} else {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
inlineMin = endMin;
}
}
if (hasBreak) {
inlineMax += beginMax;
m_maxPrefWidth = max(inlineMax, m_maxPrefWidth);
m_maxPrefWidth = max(childMax, m_maxPrefWidth);
inlineMax = endMax;
} else
inlineMax += childMax;
}
if (child->isListMarker())
stripFrontSpaces = true;
} else {
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
m_maxPrefWidth = max(inlineMax, m_maxPrefWidth);
inlineMin = inlineMax = 0;
stripFrontSpaces = true;
trailingSpaceChild = 0;
}
oldAutoWrap = autoWrap;
if (!child->isRenderInline())
previousLeaf = child;
}
if (style()->collapseWhiteSpace())
stripTrailingSpace(inlineMax, inlineMin, trailingSpaceChild);
m_minPrefWidth = max(inlineMin, m_minPrefWidth);
m_maxPrefWidth = max(inlineMax, m_maxPrefWidth);
}
#define BLOCK_MAX_WIDTH 15000
void RenderBlock::calcBlockPrefWidths()
{
bool nowrap = style()->whiteSpace() == NOWRAP;
RenderObject *child = firstChild();
int floatLeftWidth = 0, floatRightWidth = 0;
while (child) {
if (child->isPositioned()) {
child = child->nextSibling();
continue;
}
if (child->isFloating() || (child->isBox() && toRenderBox(child)->avoidsFloats())) {
int floatTotalWidth = floatLeftWidth + floatRightWidth;
if (child->style()->clear() & CLEFT) {
m_maxPrefWidth = max(floatTotalWidth, m_maxPrefWidth);
floatLeftWidth = 0;
}
if (child->style()->clear() & CRIGHT) {
m_maxPrefWidth = max(floatTotalWidth, m_maxPrefWidth);
floatRightWidth = 0;
}
}
Length ml = child->style()->marginLeft();
Length mr = child->style()->marginRight();
int margin = 0, marginLeft = 0, marginRight = 0;
if (ml.isFixed())
marginLeft += ml.value();
if (mr.isFixed())
marginRight += mr.value();
margin = marginLeft + marginRight;
int w = child->minPrefWidth() + margin;
m_minPrefWidth = max(w, m_minPrefWidth);
if (nowrap && !child->isTable())
m_maxPrefWidth = max(w, m_maxPrefWidth);
w = child->maxPrefWidth() + margin;
if (!child->isFloating()) {
if (child->isBox() && toRenderBox(child)->avoidsFloats()) {
int maxLeft = marginLeft > 0 ? max(floatLeftWidth, marginLeft) : floatLeftWidth + marginLeft;
int maxRight = marginRight > 0 ? max(floatRightWidth, marginRight) : floatRightWidth + marginRight;
w = child->maxPrefWidth() + maxLeft + maxRight;
w = max(w, floatLeftWidth + floatRightWidth);
}
else
m_maxPrefWidth = max(floatLeftWidth + floatRightWidth, m_maxPrefWidth);
floatLeftWidth = floatRightWidth = 0;
}
if (child->isFloating()) {
if (style()->floating() == FLEFT)
floatLeftWidth += w;
else
floatRightWidth += w;
} else
m_maxPrefWidth = max(w, m_maxPrefWidth);
if (style()->htmlHacks() && child->style()->width().isPercent() &&
!isTableCell() && child->isTable() && m_maxPrefWidth < BLOCK_MAX_WIDTH) {
RenderBlock* cb = containingBlock();
while (!cb->isRenderView() && !cb->isTableCell())
cb = cb->containingBlock();
if (!cb->isTableCell())
m_maxPrefWidth = BLOCK_MAX_WIDTH;
}
child = child->nextSibling();
}
m_minPrefWidth = max(0, m_minPrefWidth);
m_maxPrefWidth = max(0, m_maxPrefWidth);
m_maxPrefWidth = max(floatLeftWidth + floatRightWidth, m_maxPrefWidth);
}
bool RenderBlock::hasLineIfEmpty() const
{
if (!node())
return false;
if (node()->isContentEditable() && node()->rootEditableElement() == node())
return true;
if (node()->isShadowNode() && (node()->shadowParentNode()->hasTagName(inputTag) || node()->shadowParentNode()->hasTagName(textareaTag)))
return true;
return false;
}
int RenderBlock::lineHeight(bool firstLine, bool isRootLineBox) const
{
if (isReplaced() && !isRootLineBox)
return height() + marginTop() + marginBottom();
if (firstLine && document()->usesFirstLineRules()) {
RenderStyle* s = style(firstLine);
if (s != style())
return s->computedLineHeight();
}
if (m_lineHeight == -1)
m_lineHeight = style()->computedLineHeight();
return m_lineHeight;
}
int RenderBlock::baselinePosition(bool b, bool isRootLineBox) const
{
if (isReplaced() && !isRootLineBox) {
if (style()->hasAppearance() && !theme()->isControlContainer(style()->appearance()))
return theme()->baselinePosition(this);
int baselinePos = (layer() && (layer()->marquee() || layer()->verticalScrollbar() || layer()->scrollYOffset() != 0)) ? -1 : lastLineBoxBaseline();
if (baselinePos != -1 && baselinePos <= borderTop() + paddingTop() + contentHeight())
return marginTop() + baselinePos;
return height() + marginTop() + marginBottom();
}
return RenderBox::baselinePosition(b, isRootLineBox);
}
int RenderBlock::firstLineBoxBaseline() const
{
if (!isBlockFlow())
return -1;
if (childrenInline()) {
if (firstLineBox())
return firstLineBox()->y() + style(true)->font().ascent();
else
return -1;
}
else {
for (RenderBox* curr = firstChildBox(); curr; curr = curr->nextSiblingBox()) {
if (!curr->isFloatingOrPositioned()) {
int result = curr->firstLineBoxBaseline();
if (result != -1)
return curr->y() + result; }
}
}
return -1;
}
int RenderBlock::lastLineBoxBaseline() const
{
if (!isBlockFlow())
return -1;
if (childrenInline()) {
if (!firstLineBox() && hasLineIfEmpty())
return RenderBox::baselinePosition(true, true) + borderTop() + paddingTop();
if (lastLineBox())
return lastLineBox()->y() + style(lastLineBox() == firstLineBox())->font().ascent();
return -1;
}
else {
bool haveNormalFlowChild = false;
for (RenderBox* curr = lastChildBox(); curr; curr = curr->previousSiblingBox()) {
if (!curr->isFloatingOrPositioned()) {
haveNormalFlowChild = true;
int result = curr->lastLineBoxBaseline();
if (result != -1)
return curr->y() + result; }
}
if (!haveNormalFlowChild && hasLineIfEmpty())
return RenderBox::baselinePosition(true, true) + borderTop() + paddingTop();
}
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;
}
void RenderBlock::updateFirstLetter()
{
if (!document()->usesFirstLetterRules())
return;
if (style()->styleType() == FIRST_LETTER)
return;
RenderObject* firstLetterBlock = this;
bool hasPseudoStyle = false;
while (true) {
hasPseudoStyle = firstLetterBlock->style()->hasPseudoStyle(FIRST_LETTER)
&& firstLetterBlock->canHaveChildren();
if (hasPseudoStyle)
break;
RenderObject* parentBlock = firstLetterBlock->parent();
if (firstLetterBlock->isReplaced() || !parentBlock || parentBlock->firstChild() != firstLetterBlock ||
!parentBlock->isBlockFlow())
break;
firstLetterBlock = parentBlock;
}
if (!hasPseudoStyle)
return;
RenderObject* currChild = firstLetterBlock->firstChild();
while (currChild && ((!currChild->isReplaced() && !currChild->isRenderButton() && !currChild->isMenuList()) || currChild->isFloatingOrPositioned()) && !currChild->isText()) {
if (currChild->isFloatingOrPositioned()) {
if (currChild->style()->styleType() == FIRST_LETTER) {
currChild = currChild->firstChild();
break;
}
currChild = currChild->nextSibling();
} else
currChild = currChild->firstChild();
}
while (currChild && currChild->isListMarker())
currChild = currChild->nextSibling();
if (!currChild)
return;
if (currChild->parent()->style()->styleType() == FIRST_LETTER) {
RenderObject* firstLetter = currChild->parent();
RenderObject* firstLetterContainer = firstLetter->parent();
RenderStyle* pseudoStyle = styleForFirstLetter(firstLetterBlock, firstLetterContainer);
if (Node::diff(firstLetter->style(), pseudoStyle) == Node::Detach) {
RenderObject* newFirstLetter;
if (pseudoStyle->display() == INLINE)
newFirstLetter = new (renderArena()) RenderInline(document());
else
newFirstLetter = new (renderArena()) RenderBlock(document());
newFirstLetter->setStyle(pseudoStyle);
view()->disableLayoutState();
while (RenderObject* child = firstLetter->firstChild()) {
if (child->isText())
toRenderText(child)->dirtyLineBoxes(true);
firstLetter->removeChild(child);
newFirstLetter->addChild(child, 0);
}
RenderTextFragment* remainingText = toRenderTextFragment(firstLetter->nextSibling());
ASSERT(remainingText->node()->renderer() == remainingText);
remainingText->setFirstLetter(newFirstLetter);
firstLetter->destroy();
firstLetter = newFirstLetter;
firstLetterContainer->addChild(firstLetter, remainingText);
view()->enableLayoutState();
} else
firstLetter->setStyle(pseudoStyle);
for (RenderObject* genChild = firstLetter->firstChild(); genChild; genChild = genChild->nextSibling()) {
if (genChild->isText())
genChild->setStyle(pseudoStyle);
}
return;
}
if (!currChild->isText() || currChild->isBR())
return;
RenderObject* firstLetterContainer = currChild->parent();
view()->disableLayoutState();
RenderText* textObj = toRenderText(currChild);
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, currChild);
RefPtr<StringImpl> oldText = textObj->originalText();
ASSERT(oldText);
if (oldText && oldText->length() > 0) {
unsigned length = 0;
while (length < oldText->length() && (isSpaceOrNewline((*oldText)[length]) || Unicode::isPunct((*oldText)[length])))
length++;
length++;
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);
RenderObject* nextObj = textObj->nextSibling();
firstLetterContainer->removeChild(textObj);
firstLetterContainer->addChild(remainingText, nextObj);
remainingText->setFirstLetter(firstLetter);
RenderTextFragment* letter =
new (renderArena()) RenderTextFragment(remainingText->node() ? remainingText->node() : remainingText->document(), oldText.get(), 0, length);
letter->setStyle(pseudoStyle);
firstLetter->addChild(letter);
textObj->destroy();
}
view()->enableLayoutState();
}
static bool shouldCheckLines(RenderObject* obj)
{
return !obj->isFloatingOrPositioned() && !obj->isRunIn() &&
obj->isBlockFlow() && obj->style()->height().isAuto() &&
(!obj->isFlexibleBox() || 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()) : 0);
}
}
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()) : 0);
}
else if (!obj->isFloatingOrPositioned() && !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(int x, int& left, int& right) const
{
if (style()->visibility() == VISIBLE) {
if (childrenInline()) {
for (RootInlineBox* box = firstRootBox(); box; box = box->nextRootBox()) {
if (box->firstChild())
left = min(left, x + box->firstChild()->x());
if (box->lastChild())
right = max(right, x + box->lastChild()->x() + box->lastChild()->width());
}
}
else {
for (RenderBox* obj = firstChildBox(); obj; obj = obj->nextSiblingBox()) {
if (!obj->isFloatingOrPositioned()) {
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) {
FloatingObject* r;
DeprecatedPtrListIterator<FloatingObject> it(*m_floatingObjects);
for (; (r = it.current()); ++it) {
if (r->m_shouldPaint) {
int floatLeft = r->m_left - r->m_renderer->x() + r->m_renderer->marginLeft();
int floatRight = floatLeft + r->m_renderer->width();
left = min(left, floatLeft);
right = max(right, floatRight);
}
}
}
}
}
void RenderBlock::borderFitAdjust(int& x, int& w) const
{
if (style()->borderFit() == BorderFitBorder)
return;
int left = INT_MAX;
int right = INT_MIN;
int oldWidth = w;
adjustForBorderFit(0, left, right);
if (left != INT_MAX) {
left -= (borderLeft() + paddingLeft());
if (left > 0) {
x += left;
w -= left;
}
}
if (right != INT_MIN) {
right += (borderRight() + paddingRight());
if (right < oldWidth)
w -= (oldWidth - right);
}
}
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::setMaxTopMargins(int pos, int neg)
{
if (!m_maxMargin) {
if (pos == MaxMargin::topPosDefault(this) && neg == MaxMargin::topNegDefault(this))
return;
m_maxMargin = new MaxMargin(this);
}
m_maxMargin->m_topPos = pos;
m_maxMargin->m_topNeg = neg;
}
void RenderBlock::setMaxBottomMargins(int pos, int neg)
{
if (!m_maxMargin) {
if (pos == MaxMargin::bottomPosDefault(this) && neg == MaxMargin::bottomNegDefault(this))
return;
m_maxMargin = new MaxMargin(this);
}
m_maxMargin->m_bottomPos = pos;
m_maxMargin->m_bottomNeg = neg;
}
void RenderBlock::absoluteRects(Vector<IntRect>& rects, int tx, int ty)
{
if (inlineContinuation()) {
rects.append(IntRect(tx, ty - collapsedMarginTop(),
width(), height() + collapsedMarginTop() + collapsedMarginBottom()));
inlineContinuation()->absoluteRects(rects,
tx - x() + inlineContinuation()->containingBlock()->x(),
ty - y() + inlineContinuation()->containingBlock()->y());
} else
rects.append(IntRect(tx, ty, width(), height()));
}
void RenderBlock::absoluteQuads(Vector<FloatQuad>& quads)
{
if (inlineContinuation()) {
FloatRect localRect(0, -collapsedMarginTop(),
width(), height() + collapsedMarginTop() + collapsedMarginBottom());
quads.append(localToAbsoluteQuad(localRect));
inlineContinuation()->absoluteQuads(quads);
} else
quads.append(RenderBox::localToAbsoluteQuad(FloatRect(0, 0, width(), height())));
}
IntRect RenderBlock::rectWithOutlineForRepaint(RenderBoxModelObject* repaintContainer, int outlineWidth)
{
IntRect r(RenderBox::rectWithOutlineForRepaint(repaintContainer, outlineWidth));
if (inlineContinuation())
r.inflateY(collapsedMarginTop());
return r;
}
RenderObject* RenderBlock::hoverAncestor() const
{
return inlineContinuation() ? inlineContinuation() : RenderBox::hoverAncestor();
}
void RenderBlock::updateDragState(bool dragOn)
{
RenderBox::updateDragState(dragOn);
if (inlineContinuation())
inlineContinuation()->updateDragState(dragOn);
}
RenderStyle* RenderBlock::outlineStyleForRepaint() const
{
return inlineContinuation() ? inlineContinuation()->style() : style();
}
void RenderBlock::childBecameNonInline(RenderObject*)
{
makeChildrenNonInline();
if (isAnonymousBlock() && parent() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
}
void RenderBlock::updateHitTestResult(HitTestResult& result, const IntPoint& point)
{
if (result.innerNode())
return;
Node* n = node();
if (inlineContinuation())
n = inlineContinuation()->node();
if (n) {
result.setInnerNode(n);
if (!result.innerNonSharedNode())
result.setInnerNonSharedNode(n);
result.setLocalPoint(point);
}
}
IntRect RenderBlock::localCaretRect(InlineBox* inlineBox, int caretOffset, int* extraWidthToEndOfLine)
{
if (firstChild())
return RenderBox::localCaretRect(inlineBox, caretOffset, extraWidthToEndOfLine);
RenderStyle* currentStyle = firstLineStyle();
int height = lineHeight(true);
enum CaretAlignment { alignLeft, alignRight, alignCenter };
CaretAlignment alignment = alignLeft;
switch (currentStyle->textAlign()) {
case TAAUTO:
case JUSTIFY:
if (currentStyle->direction() == RTL)
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;
}
int x = borderLeft() + paddingLeft();
int w = width();
switch (alignment) {
case alignLeft:
break;
case alignCenter:
x = (x + w - (borderRight() + paddingRight())) / 2;
break;
case alignRight:
x = w - (borderRight() + paddingRight()) - caretWidth;
break;
}
if (extraWidthToEndOfLine) {
if (isRenderBlock()) {
*extraWidthToEndOfLine = w - (x + caretWidth);
} else {
int myRight = x + caretWidth;
FloatPoint absRightPoint = localToAbsolute(FloatPoint(myRight, 0));
int containerRight = containingBlock()->x() + containingBlockWidthForContent();
FloatPoint absContainerPoint = localToAbsolute(FloatPoint(containerRight, 0));
*extraWidthToEndOfLine = absContainerPoint.x() - absRightPoint.x();
}
}
int y = paddingTop() + borderTop();
return IntRect(x, y, caretWidth, height);
}
void RenderBlock::addFocusRingRects(Vector<IntRect>& rects, int tx, int ty)
{
if (inlineContinuation()) {
bool nextInlineHasLineBox = inlineContinuation()->firstLineBox();
bool prevInlineHasLineBox = toRenderInline(inlineContinuation()->node()->renderer())->firstLineBox();
int topMargin = prevInlineHasLineBox ? collapsedMarginTop() : 0;
int bottomMargin = nextInlineHasLineBox ? collapsedMarginBottom() : 0;
IntRect rect(tx, ty - topMargin, width(), height() + topMargin + bottomMargin);
if (!rect.isEmpty())
rects.append(rect);
} else if (width() && height())
rects.append(IntRect(tx, ty, width(), height()));
if (!hasOverflowClip() && !hasControlClip()) {
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
int top = max(curr->lineTop(), curr->y());
int bottom = min(curr->lineBottom(), curr->y() + curr->height());
IntRect rect(tx + curr->x(), ty + top, curr->width(), bottom - top);
if (!rect.isEmpty())
rects.append(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(tx + box->x(), ty + box->y());
box->addFocusRingRects(rects, pos.x(), pos.y());
}
}
}
if (inlineContinuation())
inlineContinuation()->addFocusRingRects(rects,
tx - x() + inlineContinuation()->containingBlock()->x(),
ty - y() + inlineContinuation()->containingBlock()->y());
}
RenderBlock* RenderBlock::createAnonymousBlock(bool isFlexibleBox) const
{
RefPtr<RenderStyle> newStyle = RenderStyle::create();
newStyle->inheritFrom(style());
RenderBlock* newBox = 0;
if (isFlexibleBox) {
newStyle->setDisplay(BOX);
newBox = new (renderArena()) RenderFlexibleBox(document() );
} else {
newStyle->setDisplay(BLOCK);
newBox = new (renderArena()) RenderBlock(document() );
}
newBox->setStyle(newStyle.release());
return newBox;
}
const char* RenderBlock::renderName() const
{
if (isBody())
return "RenderBody";
if (isFloating())
return "RenderBlock (floating)";
if (isPositioned())
return "RenderBlock (positioned)";
if (isAnonymousBlock())
return "RenderBlock (anonymous)";
else if (isAnonymous())
return "RenderBlock (generated)";
if (isRelPositioned())
return "RenderBlock (relative positioned)";
if (isRunIn())
return "RenderBlock (run-in)";
return "RenderBlock";
}
#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()->isShadowNode()) {
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);
}
}
}
}
}