2 * Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
21 #include "RootInlineBox.h"
23 #include "BidiResolver.h"
25 #include "ChromeClient.h"
27 #include "EllipsisBox.h"
29 #include "GraphicsContext.h"
30 #include "HitTestResult.h"
31 #include "InlineTextBox.h"
32 #include "LogicalSelectionOffsetCaches.h"
34 #include "PaintInfo.h"
35 #include "RenderArena.h"
36 #include "RenderBlock.h"
37 #include "RenderFlowThread.h"
38 #include "RenderView.h"
39 #include "VerticalPositionCache.h"
40 #include <wtf/unicode/Unicode.h>
46 struct SameSizeAsRootInlineBox : public InlineFlowBox {
47 unsigned variables[5];
51 COMPILE_ASSERT(sizeof(RootInlineBox) == sizeof(SameSizeAsRootInlineBox), RootInlineBox_should_stay_small);
53 typedef WTF::HashMap<const RootInlineBox*, EllipsisBox*> EllipsisBoxMap;
54 static EllipsisBoxMap* gEllipsisBoxMap = 0;
56 RootInlineBox::RootInlineBox(RenderBlock& block)
57 : InlineFlowBox(block)
62 , m_lineTopWithLeading(0)
63 , m_lineBottomWithLeading(0)
65 setIsHorizontal(block.isHorizontalWritingMode());
69 void RootInlineBox::destroy(RenderArena& arena)
71 detachEllipsisBox(arena);
72 InlineFlowBox::destroy(arena);
75 void RootInlineBox::detachEllipsisBox(RenderArena& arena)
77 if (hasEllipsisBox()) {
78 EllipsisBox* box = gEllipsisBoxMap->take(this);
81 setHasEllipsisBox(false);
85 RenderLineBoxList& RootInlineBox::rendererLineBoxes() const
87 return block().lineBoxes();
90 void RootInlineBox::clearTruncation()
92 if (hasEllipsisBox()) {
93 detachEllipsisBox(renderer().renderArena());
94 InlineFlowBox::clearTruncation();
98 bool RootInlineBox::isHyphenated() const
100 for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
101 if (box->isInlineTextBox()) {
102 if (toInlineTextBox(box)->hasHyphen())
110 int RootInlineBox::baselinePosition(FontBaseline baselineType) const
112 return boxModelObject()->baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
115 LayoutUnit RootInlineBox::lineHeight() const
117 return boxModelObject()->lineHeight(isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
120 bool RootInlineBox::lineCanAccommodateEllipsis(bool ltr, int blockEdge, int lineBoxEdge, int ellipsisWidth)
122 // First sanity-check the unoverflowed width of the whole line to see if there is sufficient room.
123 int delta = ltr ? lineBoxEdge - blockEdge : blockEdge - lineBoxEdge;
124 if (logicalWidth() - delta < ellipsisWidth)
127 // Next iterate over all the line boxes on the line. If we find a replaced element that intersects
128 // then we refuse to accommodate the ellipsis. Otherwise we're ok.
129 return InlineFlowBox::canAccommodateEllipsis(ltr, blockEdge, ellipsisWidth);
132 float RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr, bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth,
133 InlineBox* markupBox)
135 // Create an ellipsis box.
136 EllipsisBox* ellipsisBox = new (renderer().renderArena()) EllipsisBox(block(), ellipsisStr, this,
137 ellipsisWidth - (markupBox ? markupBox->logicalWidth() : 0), logicalHeight(),
138 y(), !prevRootBox(), isHorizontal(), markupBox);
140 if (!gEllipsisBoxMap)
141 gEllipsisBoxMap = new EllipsisBoxMap();
142 gEllipsisBoxMap->add(this, ellipsisBox);
143 setHasEllipsisBox(true);
145 // FIXME: Do we need an RTL version of this?
146 if (ltr && (x() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
147 ellipsisBox->setX(x() + logicalWidth());
148 return logicalWidth() + ellipsisWidth;
151 // Now attempt to find the nearest glyph horizontally and place just to the right (or left in RTL)
152 // of that glyph. Mark all of the objects that intersect the ellipsis box as not painting (as being
154 bool foundBox = false;
155 float truncatedWidth = 0;
156 float position = placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
157 ellipsisBox->setX(position);
158 return truncatedWidth;
161 float RootInlineBox::placeEllipsisBox(bool ltr, float blockLeftEdge, float blockRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
163 float result = InlineFlowBox::placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
165 result = ltr ? blockRightEdge - ellipsisWidth : blockLeftEdge;
166 truncatedWidth = blockRightEdge - blockLeftEdge;
171 void RootInlineBox::paintEllipsisBox(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom) const
173 if (hasEllipsisBox() && paintInfo.shouldPaintWithinRoot(&renderer()) && renderer().style()->visibility() == VISIBLE
174 && paintInfo.phase == PaintPhaseForeground)
175 ellipsisBox()->paint(paintInfo, paintOffset, lineTop, lineBottom);
180 void RootInlineBox::addHighlightOverflow()
182 Page* page = renderer().frame().page();
186 // Highlight acts as a selection inflation.
187 FloatRect rootRect(0, selectionTop(), logicalWidth(), selectionHeight());
188 IntRect inflatedRect = enclosingIntRect(page->chrome().client().customHighlightRect(renderer().element(), renderer().style()->highlight(), rootRect));
189 setOverflowFromLogicalRects(inflatedRect, inflatedRect, lineTop(), lineBottom());
192 void RootInlineBox::paintCustomHighlight(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const AtomicString& highlightType)
194 if (!paintInfo.shouldPaintWithinRoot(&renderer()) || renderer().style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseForeground)
197 Page* page = renderer().frame().page();
201 // Get the inflated rect so that we can properly hit test.
202 FloatRect rootRect(paintOffset.x() + x(), paintOffset.y() + selectionTop(), logicalWidth(), selectionHeight());
203 FloatRect inflatedRect = page->chrome().client().customHighlightRect(renderer().element(), highlightType, rootRect);
204 if (inflatedRect.intersects(paintInfo.rect))
205 page->chrome().client().paintCustomHighlight(renderer().element(), highlightType, rootRect, rootRect, false, true);
210 void RootInlineBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
212 InlineFlowBox::paint(paintInfo, paintOffset, lineTop, lineBottom);
213 paintEllipsisBox(paintInfo, paintOffset, lineTop, lineBottom);
215 RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
216 if (styleToUse->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
217 paintCustomHighlight(paintInfo, paintOffset, styleToUse->highlight());
221 bool RootInlineBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
223 if (hasEllipsisBox() && visibleToHitTesting()) {
224 if (ellipsisBox()->nodeAtPoint(request, result, locationInContainer, accumulatedOffset, lineTop, lineBottom)) {
225 renderer().updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset));
229 return InlineFlowBox::nodeAtPoint(request, result, locationInContainer, accumulatedOffset, lineTop, lineBottom);
232 void RootInlineBox::adjustPosition(float dx, float dy)
234 InlineFlowBox::adjustPosition(dx, dy);
235 LayoutUnit blockDirectionDelta = isHorizontal() ? dy : dx; // The block direction delta is a LayoutUnit.
236 m_lineTop += blockDirectionDelta;
237 m_lineBottom += blockDirectionDelta;
238 m_lineTopWithLeading += blockDirectionDelta;
239 m_lineBottomWithLeading += blockDirectionDelta;
240 if (hasEllipsisBox())
241 ellipsisBox()->adjustPosition(dx, dy);
244 void RootInlineBox::childRemoved(InlineBox* box)
246 if (&box->renderer() == m_lineBreakObj)
247 setLineBreakInfo(0, 0, BidiStatus());
249 for (RootInlineBox* prev = prevRootBox(); prev && prev->lineBreakObj() == &box->renderer(); prev = prev->prevRootBox()) {
250 prev->setLineBreakInfo(0, 0, BidiStatus());
255 RenderRegion* RootInlineBox::containingRegion() const
257 RenderRegion* region = m_fragmentationData ? m_fragmentationData->m_containingRegion : 0;
261 RenderFlowThread* flowThread = block().flowThreadContainingBlock();
262 const RenderRegionList& regionList = flowThread->renderRegionList();
263 ASSERT(regionList.contains(region));
270 void RootInlineBox::setContainingRegion(RenderRegion* region)
273 ASSERT(block().flowThreadContainingBlock());
274 LineFragmentationData* fragmentationData = ensureLineFragmentationData();
275 fragmentationData->m_containingRegion = region;
278 LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
281 // SVG will handle vertical alignment on its own.
282 if (isSVGRootInlineBox())
286 LayoutUnit maxPositionTop = 0;
287 LayoutUnit maxPositionBottom = 0;
290 bool setMaxAscent = false;
291 bool setMaxDescent = false;
293 // Figure out if we're in no-quirks mode.
294 bool noQuirksMode = renderer().document().inNoQuirksMode();
296 m_baselineType = requiresIdeographicBaseline(textBoxDataMap) ? IdeographicBaseline : AlphabeticBaseline;
298 computeLogicalBoxHeights(this, maxPositionTop, maxPositionBottom, maxAscent, maxDescent, setMaxAscent, setMaxDescent, noQuirksMode,
299 textBoxDataMap, baselineType(), verticalPositionCache);
301 if (maxAscent + maxDescent < max(maxPositionTop, maxPositionBottom))
302 adjustMaxAscentAndDescent(maxAscent, maxDescent, maxPositionTop, maxPositionBottom);
304 LayoutUnit maxHeight = maxAscent + maxDescent;
305 LayoutUnit lineTop = heightOfBlock;
306 LayoutUnit lineBottom = heightOfBlock;
307 LayoutUnit lineTopIncludingMargins = heightOfBlock;
308 LayoutUnit lineBottomIncludingMargins = heightOfBlock;
309 bool setLineTop = false;
310 bool hasAnnotationsBefore = false;
311 bool hasAnnotationsAfter = false;
312 placeBoxesInBlockDirection(heightOfBlock, maxHeight, maxAscent, noQuirksMode, lineTop, lineBottom, setLineTop,
313 lineTopIncludingMargins, lineBottomIncludingMargins, hasAnnotationsBefore, hasAnnotationsAfter, baselineType());
314 m_hasAnnotationsBefore = hasAnnotationsBefore;
315 m_hasAnnotationsAfter = hasAnnotationsAfter;
317 maxHeight = max<LayoutUnit>(0, maxHeight); // FIXME: Is this really necessary?
319 setLineTopBottomPositions(lineTop, lineBottom, heightOfBlock, heightOfBlock + maxHeight);
320 setPaginatedLineWidth(block().availableLogicalWidthForContent(heightOfBlock));
322 LayoutUnit annotationsAdjustment = beforeAnnotationsAdjustment();
323 if (annotationsAdjustment) {
324 // FIXME: Need to handle pagination here. We might have to move to the next page/column as a result of the
326 adjustBlockDirectionPosition(annotationsAdjustment);
327 heightOfBlock += annotationsAdjustment;
330 LayoutUnit gridSnapAdjustment = lineSnapAdjustment();
331 if (gridSnapAdjustment) {
332 adjustBlockDirectionPosition(gridSnapAdjustment);
333 heightOfBlock += gridSnapAdjustment;
336 return heightOfBlock + maxHeight;
339 #if ENABLE(CSS3_TEXT)
340 float RootInlineBox::maxLogicalTop() const
342 float maxLogicalTop = 0;
343 computeMaxLogicalTop(maxLogicalTop);
344 return maxLogicalTop;
348 LayoutUnit RootInlineBox::beforeAnnotationsAdjustment() const
350 LayoutUnit result = 0;
352 if (!renderer().style()->isFlippedLinesWritingMode()) {
353 // Annotations under the previous line may push us down.
354 if (prevRootBox() && prevRootBox()->hasAnnotationsAfter())
355 result = prevRootBox()->computeUnderAnnotationAdjustment(lineTop());
357 if (!hasAnnotationsBefore())
360 // Annotations over this line may push us further down.
361 LayoutUnit highestAllowedPosition = prevRootBox() ? min(prevRootBox()->lineBottom(), lineTop()) + result : static_cast<LayoutUnit>(block().borderBefore());
362 result = computeOverAnnotationAdjustment(highestAllowedPosition);
364 // Annotations under this line may push us up.
365 if (hasAnnotationsBefore())
366 result = computeUnderAnnotationAdjustment(prevRootBox() ? prevRootBox()->lineBottom() : static_cast<LayoutUnit>(block().borderBefore()));
368 if (!prevRootBox() || !prevRootBox()->hasAnnotationsAfter())
371 // We have to compute the expansion for annotations over the previous line to see how much we should move.
372 LayoutUnit lowestAllowedPosition = max(prevRootBox()->lineBottom(), lineTop()) - result;
373 result = prevRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
379 LayoutUnit RootInlineBox::lineSnapAdjustment(LayoutUnit delta) const
381 // If our block doesn't have snapping turned on, do nothing.
382 // FIXME: Implement bounds snapping.
383 if (block().style()->lineSnap() == LineSnapNone)
386 // Get the current line grid and offset.
387 LayoutState* layoutState = block().view().layoutState();
388 RenderBlock* lineGrid = layoutState->lineGrid();
389 LayoutSize lineGridOffset = layoutState->lineGridOffset();
390 if (!lineGrid || lineGrid->style()->writingMode() != block().style()->writingMode())
393 // Get the hypothetical line box used to establish the grid.
394 RootInlineBox* lineGridBox = lineGrid->lineGridBox();
398 LayoutUnit lineGridBlockOffset = lineGrid->isHorizontalWritingMode() ? lineGridOffset.height() : lineGridOffset.width();
399 LayoutUnit blockOffset = block().isHorizontalWritingMode() ? layoutState->layoutOffset().height() : layoutState->layoutOffset().width();
401 // Now determine our position on the grid. Our baseline needs to be adjusted to the nearest baseline multiple
402 // as established by the line box.
403 // FIXME: Need to handle crazy line-box-contain values that cause the root line box to not be considered. I assume
404 // the grid should honor line-box-contain.
405 LayoutUnit gridLineHeight = lineGridBox->lineBottomWithLeading() - lineGridBox->lineTopWithLeading();
409 LayoutUnit lineGridFontAscent = lineGrid->style()->fontMetrics().ascent(baselineType());
410 LayoutUnit lineGridFontHeight = lineGridBox->logicalHeight();
411 LayoutUnit firstTextTop = lineGridBlockOffset + lineGridBox->logicalTop();
412 LayoutUnit firstLineTopWithLeading = lineGridBlockOffset + lineGridBox->lineTopWithLeading();
413 LayoutUnit firstBaselinePosition = firstTextTop + lineGridFontAscent;
415 LayoutUnit currentTextTop = blockOffset + logicalTop() + delta;
416 LayoutUnit currentFontAscent = block().style()->fontMetrics().ascent(baselineType());
417 LayoutUnit currentBaselinePosition = currentTextTop + currentFontAscent;
419 LayoutUnit lineGridPaginationOrigin = isHorizontal() ? layoutState->lineGridPaginationOrigin().height() : layoutState->lineGridPaginationOrigin().width();
421 // If we're paginated, see if we're on a page after the first one. If so, the grid resets on subsequent pages.
422 // FIXME: If the grid is an ancestor of the pagination establisher, then this is incorrect.
423 LayoutUnit pageLogicalTop = 0;
424 if (layoutState->isPaginated() && layoutState->pageLogicalHeight()) {
425 pageLogicalTop = block().pageLogicalTopForOffset(lineTopWithLeading() + delta);
426 if (pageLogicalTop > firstLineTopWithLeading)
427 firstTextTop = pageLogicalTop + lineGridBox->logicalTop() - lineGrid->borderAndPaddingBefore() + lineGridPaginationOrigin;
430 if (block().style()->lineSnap() == LineSnapContain) {
431 // Compute the desired offset from the text-top of a grid line.
432 // Look at our height (logicalHeight()).
433 // Look at the total available height. It's going to be (textBottom - textTop) + (n-1)*(multiple with leading)
434 // where n is number of grid lines required to enclose us.
435 if (logicalHeight() <= lineGridFontHeight)
436 firstTextTop += (lineGridFontHeight - logicalHeight()) / 2;
438 LayoutUnit numberOfLinesWithLeading = ceilf(static_cast<float>(logicalHeight() - lineGridFontHeight) / gridLineHeight);
439 LayoutUnit totalHeight = lineGridFontHeight + numberOfLinesWithLeading * gridLineHeight;
440 firstTextTop += (totalHeight - logicalHeight()) / 2;
442 firstBaselinePosition = firstTextTop + currentFontAscent;
444 firstBaselinePosition = firstTextTop + lineGridFontAscent;
446 // If we're above the first line, just push to the first line.
447 if (currentBaselinePosition < firstBaselinePosition)
448 return delta + firstBaselinePosition - currentBaselinePosition;
450 // Otherwise we're in the middle of the grid somewhere. Just push to the next line.
451 LayoutUnit baselineOffset = currentBaselinePosition - firstBaselinePosition;
452 LayoutUnit remainder = roundToInt(baselineOffset) % roundToInt(gridLineHeight);
453 LayoutUnit result = delta;
455 result += gridLineHeight - remainder;
457 // If we aren't paginated we can return the result.
458 if (!layoutState->isPaginated() || !layoutState->pageLogicalHeight() || result == delta)
461 // We may end up shifted to a new page. We need to do a re-snap when that happens.
462 LayoutUnit newPageLogicalTop = block().pageLogicalTopForOffset(lineBottomWithLeading() + result);
463 if (newPageLogicalTop == pageLogicalTop)
466 // Put ourselves at the top of the next page to force a snap onto the new grid established by that page.
467 return lineSnapAdjustment(newPageLogicalTop - (blockOffset + lineTopWithLeading()));
470 GapRects RootInlineBox::lineSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
471 LayoutUnit selTop, LayoutUnit selHeight, const LogicalSelectionOffsetCaches& cache, const PaintInfo* paintInfo)
473 RenderObject::SelectionState lineState = selectionState();
475 bool leftGap, rightGap;
476 block().getSelectionGapInfo(lineState, leftGap, rightGap);
480 InlineBox* firstBox = firstSelectedBox();
481 InlineBox* lastBox = lastSelectedBox();
483 result.uniteLeft(block().logicalLeftSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, &firstBox->parent()->renderer(), firstBox->logicalLeft(),
484 selTop, selHeight, cache, paintInfo));
487 result.uniteRight(block().logicalRightSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, &lastBox->parent()->renderer(), lastBox->logicalRight(),
488 selTop, selHeight, cache, paintInfo));
491 // When dealing with bidi text, a non-contiguous selection region is possible.
492 // e.g. The logical text aaaAAAbbb (capitals denote RTL text and non-capitals LTR) is layed out
493 // visually as 3 text runs |aaa|bbb|AAA| if we select 4 characters from the start of the text the
494 // selection will look like (underline denotes selection):
497 // We can see that the |bbb| run is not part of the selection while the runs around it are.
498 if (firstBox && firstBox != lastBox) {
499 // Now fill in any gaps on the line that occurred between two selected elements.
500 LayoutUnit lastLogicalLeft = firstBox->logicalRight();
501 bool isPreviousBoxSelected = firstBox->selectionState() != RenderObject::SelectionNone;
502 for (InlineBox* box = firstBox->nextLeafChild(); box; box = box->nextLeafChild()) {
503 if (box->selectionState() != RenderObject::SelectionNone) {
504 LayoutRect logicalRect(lastLogicalLeft, selTop, box->logicalLeft() - lastLogicalLeft, selHeight);
505 logicalRect.move(renderer().isHorizontalWritingMode() ? offsetFromRootBlock : LayoutSize(offsetFromRootBlock.height(), offsetFromRootBlock.width()));
506 LayoutRect gapRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
507 if (isPreviousBoxSelected && gapRect.width() > 0 && gapRect.height() > 0) {
508 if (paintInfo && box->parent()->renderer().style()->visibility() == VISIBLE)
509 paintInfo->context->fillRect(gapRect, box->parent()->renderer().selectionBackgroundColor(), box->parent()->renderer().style()->colorSpace());
510 // VisibleSelection may be non-contiguous, see comment above.
511 result.uniteCenter(gapRect);
513 lastLogicalLeft = box->logicalRight();
517 isPreviousBoxSelected = box->selectionState() != RenderObject::SelectionNone;
524 IntRect RootInlineBox::computeCaretRect(float logicalLeftPosition, unsigned caretWidth, LayoutUnit* extraWidthToEndOfLine) const
526 int height = selectionHeight();
527 int top = selectionTop();
529 // Distribute the caret's width to either side of the offset.
530 float left = logicalLeftPosition;
531 int caretWidthLeftOfOffset = caretWidth / 2;
532 left -= caretWidthLeftOfOffset;
533 int caretWidthRightOfOffset = caretWidth - caretWidthLeftOfOffset;
536 float rootLeft = logicalLeft();
537 float rootRight = logicalRight();
539 if (extraWidthToEndOfLine)
540 *extraWidthToEndOfLine = (logicalWidth() + rootLeft) - (left + caretWidth);
542 RenderStyle* blockStyle = block().style();
544 bool rightAligned = false;
545 switch (blockStyle->textAlign()) {
557 rightAligned = !blockStyle->isLeftToRightDirection();
560 rightAligned = blockStyle->isLeftToRightDirection();
564 float leftEdge = std::min<float>(0, rootLeft);
565 float rightEdge = std::max<float>(block().logicalWidth(), rootRight);
568 left = std::max(left, leftEdge);
569 left = std::min(left, rootRight - caretWidth);
571 left = std::min(left, rightEdge - caretWidthRightOfOffset);
572 left = std::max(left, rootLeft);
574 return blockStyle->isHorizontalWritingMode() ? IntRect(left, top, caretWidth, height) : IntRect(top, left, height, caretWidth);
577 RenderObject::SelectionState RootInlineBox::selectionState()
579 // Walk over all of the selected boxes.
580 RenderObject::SelectionState state = RenderObject::SelectionNone;
581 for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
582 RenderObject::SelectionState boxState = box->selectionState();
583 if ((boxState == RenderObject::SelectionStart && state == RenderObject::SelectionEnd) ||
584 (boxState == RenderObject::SelectionEnd && state == RenderObject::SelectionStart))
585 state = RenderObject::SelectionBoth;
586 else if (state == RenderObject::SelectionNone ||
587 ((boxState == RenderObject::SelectionStart || boxState == RenderObject::SelectionEnd) &&
588 (state == RenderObject::SelectionNone || state == RenderObject::SelectionInside)))
590 else if (boxState == RenderObject::SelectionNone && state == RenderObject::SelectionStart) {
591 // We are past the end of the selection.
592 state = RenderObject::SelectionBoth;
594 if (state == RenderObject::SelectionBoth)
601 InlineBox* RootInlineBox::firstSelectedBox()
603 for (InlineBox* box = firstLeafChild(); box; box = box->nextLeafChild()) {
604 if (box->selectionState() != RenderObject::SelectionNone)
611 InlineBox* RootInlineBox::lastSelectedBox()
613 for (InlineBox* box = lastLeafChild(); box; box = box->prevLeafChild()) {
614 if (box->selectionState() != RenderObject::SelectionNone)
621 LayoutUnit RootInlineBox::selectionTop() const
623 LayoutUnit selectionTop = m_lineTop;
625 if (m_hasAnnotationsBefore)
626 selectionTop -= !renderer().style()->isFlippedLinesWritingMode() ? computeOverAnnotationAdjustment(m_lineTop) : computeUnderAnnotationAdjustment(m_lineTop);
628 if (renderer().style()->isFlippedLinesWritingMode())
631 LayoutUnit prevBottom = prevRootBox() ? prevRootBox()->selectionBottom() : block().borderAndPaddingBefore();
632 if (prevBottom < selectionTop && block().containsFloats()) {
633 // This line has actually been moved further down, probably from a large line-height, but possibly because the
634 // line was forced to clear floats. If so, let's check the offsets, and only be willing to use the previous
635 // line's bottom if the offsets are greater on both sides.
636 LayoutUnit prevLeft = block().logicalLeftOffsetForLine(prevBottom, false);
637 LayoutUnit prevRight = block().logicalRightOffsetForLine(prevBottom, false);
638 LayoutUnit newLeft = block().logicalLeftOffsetForLine(selectionTop, false);
639 LayoutUnit newRight = block().logicalRightOffsetForLine(selectionTop, false);
640 if (prevLeft > newLeft || prevRight < newRight)
647 LayoutUnit RootInlineBox::selectionTopAdjustedForPrecedingBlock() const
649 const RootInlineBox& rootBox = root();
650 LayoutUnit top = selectionTop();
652 RenderObject::SelectionState blockSelectionState = rootBox.block().selectionState();
653 if (blockSelectionState != RenderObject::SelectionInside && blockSelectionState != RenderObject::SelectionEnd)
656 LayoutSize offsetToBlockBefore;
657 if (RenderBlock* block = rootBox.block().blockBeforeWithinSelectionRoot(offsetToBlockBefore)) {
658 if (RootInlineBox* lastLine = block->lastRootBox()) {
659 RenderObject::SelectionState lastLineSelectionState = lastLine->selectionState();
660 if (lastLineSelectionState != RenderObject::SelectionInside && lastLineSelectionState != RenderObject::SelectionStart)
663 LayoutUnit lastLineSelectionBottom = lastLine->selectionBottom() + offsetToBlockBefore.height();
664 top = max(top, lastLineSelectionBottom);
671 LayoutUnit RootInlineBox::selectionBottom() const
673 LayoutUnit selectionBottom = m_lineBottom;
675 if (m_hasAnnotationsAfter)
676 selectionBottom += !renderer().style()->isFlippedLinesWritingMode() ? computeUnderAnnotationAdjustment(m_lineBottom) : computeOverAnnotationAdjustment(m_lineBottom);
678 if (!renderer().style()->isFlippedLinesWritingMode() || !nextRootBox())
679 return selectionBottom;
681 LayoutUnit nextTop = nextRootBox()->selectionTop();
682 if (nextTop > selectionBottom && block().containsFloats()) {
683 // The next line has actually been moved further over, probably from a large line-height, but possibly because the
684 // line was forced to clear floats. If so, let's check the offsets, and only be willing to use the next
685 // line's top if the offsets are greater on both sides.
686 LayoutUnit nextLeft = block().logicalLeftOffsetForLine(nextTop, false);
687 LayoutUnit nextRight = block().logicalRightOffsetForLine(nextTop, false);
688 LayoutUnit newLeft = block().logicalLeftOffsetForLine(selectionBottom, false);
689 LayoutUnit newRight = block().logicalRightOffsetForLine(selectionBottom, false);
690 if (nextLeft > newLeft || nextRight < newRight)
691 return selectionBottom;
697 int RootInlineBox::blockDirectionPointInLine() const
699 return !block().style()->isFlippedBlocksWritingMode() ? max(lineTop(), selectionTop()) : min(lineBottom(), selectionBottom());
702 RenderBlock& RootInlineBox::block() const
704 return toRenderBlock(renderer());
707 static bool isEditableLeaf(InlineBox* leaf)
709 return leaf && leaf->renderer().node() && leaf->renderer().node()->rendererIsEditable();
712 InlineBox* RootInlineBox::closestLeafChildForPoint(const IntPoint& pointInContents, bool onlyEditableLeaves)
714 return closestLeafChildForLogicalLeftPosition(block().isHorizontalWritingMode() ? pointInContents.x() : pointInContents.y(), onlyEditableLeaves);
717 InlineBox* RootInlineBox::closestLeafChildForLogicalLeftPosition(int leftPosition, bool onlyEditableLeaves)
719 InlineBox* firstLeaf = firstLeafChild();
720 InlineBox* lastLeaf = lastLeafChild();
722 if (firstLeaf != lastLeaf) {
723 if (firstLeaf->isLineBreak())
724 firstLeaf = firstLeaf->nextLeafChildIgnoringLineBreak();
725 else if (lastLeaf->isLineBreak())
726 lastLeaf = lastLeaf->prevLeafChildIgnoringLineBreak();
729 if (firstLeaf == lastLeaf && (!onlyEditableLeaves || isEditableLeaf(firstLeaf)))
732 // Avoid returning a list marker when possible.
733 if (leftPosition <= firstLeaf->logicalLeft() && !firstLeaf->renderer().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(firstLeaf)))
734 // The leftPosition coordinate is less or equal to left edge of the firstLeaf.
738 if (leftPosition >= lastLeaf->logicalRight() && !lastLeaf->renderer().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(lastLeaf)))
739 // The leftPosition coordinate is greater or equal to right edge of the lastLeaf.
743 InlineBox* closestLeaf = 0;
744 for (InlineBox* leaf = firstLeaf; leaf; leaf = leaf->nextLeafChildIgnoringLineBreak()) {
745 if (!leaf->renderer().isListMarker() && (!onlyEditableLeaves || isEditableLeaf(leaf))) {
747 if (leftPosition < leaf->logicalRight())
748 // The x coordinate is less than the right edge of the box.
754 return closestLeaf ? closestLeaf : lastLeaf;
757 BidiStatus RootInlineBox::lineBreakBidiStatus() const
759 return BidiStatus(static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusEor), static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusLastStrong), static_cast<WTF::Unicode::Direction>(m_lineBreakBidiStatusLast), m_lineBreakContext);
762 void RootInlineBox::setLineBreakInfo(RenderObject* obj, unsigned breakPos, const BidiStatus& status)
764 m_lineBreakObj = obj;
765 m_lineBreakPos = breakPos;
766 m_lineBreakBidiStatusEor = status.eor;
767 m_lineBreakBidiStatusLastStrong = status.lastStrong;
768 m_lineBreakBidiStatusLast = status.last;
769 m_lineBreakContext = status.context;
772 EllipsisBox* RootInlineBox::ellipsisBox() const
774 if (!hasEllipsisBox())
776 return gEllipsisBoxMap->get(this);
779 void RootInlineBox::removeLineBoxFromRenderObject()
781 block().lineBoxes().removeLineBox(this);
784 void RootInlineBox::extractLineBoxFromRenderObject()
786 block().lineBoxes().extractLineBox(this);
789 void RootInlineBox::attachLineBoxToRenderObject()
791 block().lineBoxes().attachLineBox(this);
794 LayoutRect RootInlineBox::paddedLayoutOverflowRect(LayoutUnit endPadding) const
796 LayoutRect lineLayoutOverflow = layoutOverflowRect(lineTop(), lineBottom());
798 return lineLayoutOverflow;
800 // FIXME: Audit whether to use pixel snapped values when not using integers for layout: https://bugs.webkit.org/show_bug.cgi?id=63656
801 if (isHorizontal()) {
802 if (isLeftToRightDirection())
803 lineLayoutOverflow.shiftMaxXEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxX(), pixelSnappedLogicalRight() + endPadding));
805 lineLayoutOverflow.shiftXEdgeTo(min<LayoutUnit>(lineLayoutOverflow.x(), pixelSnappedLogicalLeft() - endPadding));
807 if (isLeftToRightDirection())
808 lineLayoutOverflow.shiftMaxYEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxY(), pixelSnappedLogicalRight() + endPadding));
810 lineLayoutOverflow.shiftYEdgeTo(min<LayoutUnit>(lineLayoutOverflow.y(), pixelSnappedLogicalLeft() - endPadding));
813 return lineLayoutOverflow;
816 static void setAscentAndDescent(int& ascent, int& descent, int newAscent, int newDescent, bool& ascentDescentSet)
818 if (!ascentDescentSet) {
819 ascentDescentSet = true;
821 descent = newDescent;
823 ascent = max(ascent, newAscent);
824 descent = max(descent, newDescent);
828 void RootInlineBox::ascentAndDescentForBox(InlineBox* box, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, int& ascent, int& descent,
829 bool& affectsAscent, bool& affectsDescent) const
831 bool ascentDescentSet = false;
833 // Replaced boxes will return 0 for the line-height if line-box-contain says they are
834 // not to be included.
835 if (box->renderer().isReplaced()) {
836 if (renderer().style(isFirstLineStyle())->lineBoxContain() & LineBoxContainReplaced) {
837 ascent = box->baselinePosition(baselineType());
838 descent = box->lineHeight() - ascent;
840 // Replaced elements always affect both the ascent and descent.
841 affectsAscent = true;
842 affectsDescent = true;
847 Vector<const SimpleFontData*>* usedFonts = 0;
848 GlyphOverflow* glyphOverflow = 0;
849 if (box->isInlineTextBox()) {
850 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.find(toInlineTextBox(box));
851 usedFonts = it == textBoxDataMap.end() ? 0 : &it->value.first;
852 glyphOverflow = it == textBoxDataMap.end() ? 0 : &it->value.second;
855 bool includeLeading = includeLeadingForBox(box);
856 bool includeFont = includeFontForBox(box);
858 bool setUsedFont = false;
859 bool setUsedFontWithLeading = false;
861 if (usedFonts && !usedFonts->isEmpty() && (includeFont || (box->renderer().style(isFirstLineStyle())->lineHeight().isNegative() && includeLeading))) {
862 usedFonts->append(box->renderer().style(isFirstLineStyle())->font().primaryFont());
863 for (size_t i = 0; i < usedFonts->size(); ++i) {
864 const FontMetrics& fontMetrics = usedFonts->at(i)->fontMetrics();
865 int usedFontAscent = fontMetrics.ascent(baselineType());
866 int usedFontDescent = fontMetrics.descent(baselineType());
867 int halfLeading = (fontMetrics.lineSpacing() - fontMetrics.height()) / 2;
868 int usedFontAscentAndLeading = usedFontAscent + halfLeading;
869 int usedFontDescentAndLeading = fontMetrics.lineSpacing() - usedFontAscentAndLeading;
871 setAscentAndDescent(ascent, descent, usedFontAscent, usedFontDescent, ascentDescentSet);
874 if (includeLeading) {
875 setAscentAndDescent(ascent, descent, usedFontAscentAndLeading, usedFontDescentAndLeading, ascentDescentSet);
876 setUsedFontWithLeading = true;
879 affectsAscent = usedFontAscent - box->logicalTop() > 0;
881 affectsDescent = usedFontDescent + box->logicalTop() > 0;
885 // If leading is included for the box, then we compute that box.
886 if (includeLeading && !setUsedFontWithLeading) {
887 int ascentWithLeading = box->baselinePosition(baselineType());
888 int descentWithLeading = box->lineHeight() - ascentWithLeading;
889 setAscentAndDescent(ascent, descent, ascentWithLeading, descentWithLeading, ascentDescentSet);
891 // Examine the font box for inline flows and text boxes to see if any part of it is above the baseline.
892 // If the top of our font box relative to the root box baseline is above the root box baseline, then
893 // we are contributing to the maxAscent value. Descent is similar. If any part of our font box is below
894 // the root box's baseline, then we contribute to the maxDescent value.
895 affectsAscent = ascentWithLeading - box->logicalTop() > 0;
896 affectsDescent = descentWithLeading + box->logicalTop() > 0;
899 if (includeFontForBox(box) && !setUsedFont) {
900 int fontAscent = box->renderer().style(isFirstLineStyle())->fontMetrics().ascent(baselineType());
901 int fontDescent = box->renderer().style(isFirstLineStyle())->fontMetrics().descent(baselineType());
902 setAscentAndDescent(ascent, descent, fontAscent, fontDescent, ascentDescentSet);
903 affectsAscent = fontAscent - box->logicalTop() > 0;
904 affectsDescent = fontDescent + box->logicalTop() > 0;
907 if (includeGlyphsForBox(box) && glyphOverflow && glyphOverflow->computeBounds) {
908 setAscentAndDescent(ascent, descent, glyphOverflow->top, glyphOverflow->bottom, ascentDescentSet);
909 affectsAscent = glyphOverflow->top - box->logicalTop() > 0;
910 affectsDescent = glyphOverflow->bottom + box->logicalTop() > 0;
911 glyphOverflow->top = min(glyphOverflow->top, max(0, glyphOverflow->top - box->renderer().style(isFirstLineStyle())->fontMetrics().ascent(baselineType())));
912 glyphOverflow->bottom = min(glyphOverflow->bottom, max(0, glyphOverflow->bottom - box->renderer().style(isFirstLineStyle())->fontMetrics().descent(baselineType())));
915 if (includeMarginForBox(box)) {
916 LayoutUnit ascentWithMargin = box->renderer().style(isFirstLineStyle())->fontMetrics().ascent(baselineType());
917 LayoutUnit descentWithMargin = box->renderer().style(isFirstLineStyle())->fontMetrics().descent(baselineType());
918 if (box->parent() && !box->renderer().isTextOrLineBreak()) {
919 ascentWithMargin += box->boxModelObject()->borderAndPaddingBefore() + box->boxModelObject()->marginBefore();
920 descentWithMargin += box->boxModelObject()->borderAndPaddingAfter() + box->boxModelObject()->marginAfter();
922 setAscentAndDescent(ascent, descent, ascentWithMargin, descentWithMargin, ascentDescentSet);
924 // Treat like a replaced element, since we're using the margin box.
925 affectsAscent = true;
926 affectsDescent = true;
930 LayoutUnit RootInlineBox::verticalPositionForBox(InlineBox* box, VerticalPositionCache& verticalPositionCache)
932 if (box->renderer().isTextOrLineBreak())
933 return box->parent()->logicalTop();
935 RenderBoxModelObject* renderer = box->boxModelObject();
936 ASSERT(renderer->isInline());
937 if (!renderer->isInline())
940 // This method determines the vertical position for inline elements.
941 bool firstLine = isFirstLineStyle();
942 if (firstLine && !renderer->document().styleSheetCollection()->usesFirstLineRules())
946 bool isRenderInline = renderer->isRenderInline();
947 if (isRenderInline && !firstLine) {
948 LayoutUnit verticalPosition = verticalPositionCache.get(renderer, baselineType());
949 if (verticalPosition != PositionUndefined)
950 return verticalPosition;
953 LayoutUnit verticalPosition = 0;
954 EVerticalAlign verticalAlign = renderer->style()->verticalAlign();
955 if (verticalAlign == TOP || verticalAlign == BOTTOM)
958 RenderObject* parent = renderer->parent();
959 if (parent->isRenderInline() && parent->style()->verticalAlign() != TOP && parent->style()->verticalAlign() != BOTTOM)
960 verticalPosition = box->parent()->logicalTop();
962 if (verticalAlign != BASELINE) {
963 const Font& font = parent->style(firstLine)->font();
964 const FontMetrics& fontMetrics = font.fontMetrics();
965 int fontSize = font.pixelSize();
967 LineDirectionMode lineDirection = parent->isHorizontalWritingMode() ? HorizontalLine : VerticalLine;
969 if (verticalAlign == SUB)
970 verticalPosition += fontSize / 5 + 1;
971 else if (verticalAlign == SUPER)
972 verticalPosition -= fontSize / 3 + 1;
973 else if (verticalAlign == TEXT_TOP)
974 verticalPosition += renderer->baselinePosition(baselineType(), firstLine, lineDirection) - fontMetrics.ascent(baselineType());
975 else if (verticalAlign == MIDDLE)
976 verticalPosition = (verticalPosition - static_cast<LayoutUnit>(fontMetrics.xHeight() / 2) - renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType(), firstLine, lineDirection)).round();
977 else if (verticalAlign == TEXT_BOTTOM) {
978 verticalPosition += fontMetrics.descent(baselineType());
979 // lineHeight - baselinePosition is always 0 for replaced elements (except inline blocks), so don't bother wasting time in that case.
980 if (!renderer->isReplaced() || renderer->isInlineBlockOrInlineTable())
981 verticalPosition -= (renderer->lineHeight(firstLine, lineDirection) - renderer->baselinePosition(baselineType(), firstLine, lineDirection));
982 } else if (verticalAlign == BASELINE_MIDDLE)
983 verticalPosition += -renderer->lineHeight(firstLine, lineDirection) / 2 + renderer->baselinePosition(baselineType(), firstLine, lineDirection);
984 else if (verticalAlign == LENGTH) {
985 LayoutUnit lineHeight;
986 //Per http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align: 'Percentages: refer to the 'line-height' of the element itself'.
987 if (renderer->style()->verticalAlignLength().isPercent())
988 lineHeight = renderer->style()->computedLineHeight();
990 lineHeight = renderer->lineHeight(firstLine, lineDirection);
991 verticalPosition -= valueForLength(renderer->style()->verticalAlignLength(), lineHeight, &renderer->view());
995 // Store the cached value.
996 if (isRenderInline && !firstLine)
997 verticalPositionCache.set(renderer, baselineType(), verticalPosition);
999 return verticalPosition;
1002 bool RootInlineBox::includeLeadingForBox(InlineBox* box) const
1004 if (box->renderer().isReplaced() || (box->renderer().isTextOrLineBreak() && !box->behavesLikeText()))
1007 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1008 return (lineBoxContain & LineBoxContainInline) || (box == this && (lineBoxContain & LineBoxContainBlock));
1011 bool RootInlineBox::includeFontForBox(InlineBox* box) const
1013 if (box->renderer().isReplaced() || (box->renderer().isTextOrLineBreak() && !box->behavesLikeText()))
1016 if (!box->behavesLikeText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
1019 // For now map "glyphs" to "font" in vertical text mode until the bounds returned by glyphs aren't garbage.
1020 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1021 return (lineBoxContain & LineBoxContainFont) || (!isHorizontal() && (lineBoxContain & LineBoxContainGlyphs));
1024 bool RootInlineBox::includeGlyphsForBox(InlineBox* box) const
1026 if (box->renderer().isReplaced() || (box->renderer().isTextOrLineBreak() && !box->behavesLikeText()))
1029 if (!box->behavesLikeText() && box->isInlineFlowBox() && !toInlineFlowBox(box)->hasTextChildren())
1032 // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
1033 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1034 return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
1037 bool RootInlineBox::includeMarginForBox(InlineBox* box) const
1039 if (box->renderer().isReplaced() || (box->renderer().isTextOrLineBreak() && !box->behavesLikeText()))
1042 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1043 return lineBoxContain & LineBoxContainInlineBox;
1047 bool RootInlineBox::fitsToGlyphs() const
1049 // FIXME: We can't fit to glyphs yet for vertical text, since the bounds returned are garbage.
1050 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1051 return isHorizontal() && (lineBoxContain & LineBoxContainGlyphs);
1054 bool RootInlineBox::includesRootLineBoxFontOrLeading() const
1056 LineBoxContain lineBoxContain = renderer().style()->lineBoxContain();
1057 return (lineBoxContain & LineBoxContainBlock) || (lineBoxContain & LineBoxContainInline) || (lineBoxContain & LineBoxContainFont);
1060 Node* RootInlineBox::getLogicalStartBoxWithNode(InlineBox*& startBox) const
1062 Vector<InlineBox*> leafBoxesInLogicalOrder;
1063 collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
1064 for (size_t i = 0; i < leafBoxesInLogicalOrder.size(); ++i) {
1065 if (leafBoxesInLogicalOrder[i]->renderer().node()) {
1066 startBox = leafBoxesInLogicalOrder[i];
1067 return startBox->renderer().node();
1074 Node* RootInlineBox::getLogicalEndBoxWithNode(InlineBox*& endBox) const
1076 Vector<InlineBox*> leafBoxesInLogicalOrder;
1077 collectLeafBoxesInLogicalOrder(leafBoxesInLogicalOrder);
1078 for (size_t i = leafBoxesInLogicalOrder.size(); i > 0; --i) {
1079 if (leafBoxesInLogicalOrder[i - 1]->renderer().node()) {
1080 endBox = leafBoxesInLogicalOrder[i - 1];
1081 return endBox->renderer().node();
1089 const char* RootInlineBox::boxName() const
1091 return "RootInlineBox";
1095 } // namespace WebCore