2 * (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 2000 Dirk Mueller (mueller@kde.org)
4 * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Library General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Library General Public License for more details.
16 * You should have received a copy of the GNU Library General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
24 #include "core/rendering/InlineTextBox.h"
26 #include "core/dom/Document.h"
27 #include "core/dom/DocumentMarkerController.h"
28 #include "core/dom/RenderedDocumentMarker.h"
29 #include "core/dom/Text.h"
30 #include "core/editing/CompositionUnderline.h"
31 #include "core/editing/CompositionUnderlineRangeFilter.h"
32 #include "core/editing/Editor.h"
33 #include "core/editing/InputMethodController.h"
34 #include "core/frame/LocalFrame.h"
35 #include "core/page/Page.h"
36 #include "core/frame/Settings.h"
37 #include "core/rendering/AbstractInlineTextBox.h"
38 #include "core/rendering/EllipsisBox.h"
39 #include "core/rendering/HitTestResult.h"
40 #include "core/rendering/PaintInfo.h"
41 #include "core/rendering/RenderBR.h"
42 #include "core/rendering/RenderBlock.h"
43 #include "core/rendering/RenderCombineText.h"
44 #include "core/rendering/RenderRubyRun.h"
45 #include "core/rendering/RenderRubyText.h"
46 #include "core/rendering/RenderTheme.h"
47 #include "core/rendering/style/ShadowList.h"
48 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
49 #include "platform/RuntimeEnabledFeatures.h"
50 #include "platform/fonts/FontCache.h"
51 #include "platform/fonts/GlyphBuffer.h"
52 #include "platform/fonts/WidthIterator.h"
53 #include "platform/graphics/GraphicsContextStateSaver.h"
54 #include "wtf/Vector.h"
55 #include "wtf/text/CString.h"
56 #include "wtf/text/StringBuilder.h"
62 struct SameSizeAsInlineTextBox : public InlineBox {
63 unsigned variables[1];
64 unsigned short variables2[2];
68 COMPILE_ASSERT(sizeof(InlineTextBox) == sizeof(SameSizeAsInlineTextBox), InlineTextBox_should_stay_small);
70 typedef WTF::HashMap<const InlineTextBox*, LayoutRect> InlineTextBoxOverflowMap;
71 static InlineTextBoxOverflowMap* gTextBoxesWithOverflow;
73 static const int misspellingLineThickness = 3;
75 void InlineTextBox::destroy()
77 AbstractInlineTextBox::willDestroy(this);
79 if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
80 gTextBoxesWithOverflow->remove(this);
84 void InlineTextBox::markDirty()
88 InlineBox::markDirty();
91 LayoutRect InlineTextBox::logicalOverflowRect() const
93 if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow)
94 return enclosingIntRect(logicalFrameRect());
95 return gTextBoxesWithOverflow->get(this);
98 void InlineTextBox::setLogicalOverflowRect(const LayoutRect& rect)
100 ASSERT(!knownToHaveNoOverflow());
101 if (!gTextBoxesWithOverflow)
102 gTextBoxesWithOverflow = new InlineTextBoxOverflowMap;
103 gTextBoxesWithOverflow->add(this, rect);
106 int InlineTextBox::baselinePosition(FontBaseline baselineType) const
108 if (!isText() || !parent())
110 if (parent()->renderer() == renderer().parent())
111 return parent()->baselinePosition(baselineType);
112 return toRenderBoxModelObject(renderer().parent())->baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
115 LayoutUnit InlineTextBox::lineHeight() const
117 if (!isText() || !renderer().parent())
119 if (renderer().isBR())
120 return toRenderBR(renderer()).lineHeight(isFirstLineStyle());
121 if (parent()->renderer() == renderer().parent())
122 return parent()->lineHeight();
123 return toRenderBoxModelObject(renderer().parent())->lineHeight(isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
126 LayoutUnit InlineTextBox::selectionTop()
128 return root().selectionTop();
131 LayoutUnit InlineTextBox::selectionBottom()
133 return root().selectionBottom();
136 LayoutUnit InlineTextBox::selectionHeight()
138 return root().selectionHeight();
141 bool InlineTextBox::isSelected(int startPos, int endPos) const
143 int sPos = std::max(startPos - m_start, 0);
144 // The position after a hard line break is considered to be past its end.
145 // See the corresponding code in InlineTextBox::selectionState.
146 int ePos = std::min(endPos - m_start, int(m_len) + (isLineBreak() ? 0 : 1));
147 return (sPos < ePos);
150 RenderObject::SelectionState InlineTextBox::selectionState()
152 RenderObject::SelectionState state = renderer().selectionState();
153 if (state == RenderObject::SelectionStart || state == RenderObject::SelectionEnd || state == RenderObject::SelectionBoth) {
154 int startPos, endPos;
155 renderer().selectionStartEnd(startPos, endPos);
156 // The position after a hard line break is considered to be past its end.
157 // See the corresponding code in InlineTextBox::isSelected.
158 int lastSelectable = start() + len() - (isLineBreak() ? 1 : 0);
160 // FIXME: Remove -webkit-line-break: LineBreakAfterWhiteSpace.
161 int endOfLineAdjustmentForCSSLineBreak = renderer().style()->lineBreak() == LineBreakAfterWhiteSpace ? -1 : 0;
162 bool start = (state != RenderObject::SelectionEnd && startPos >= m_start && startPos <= m_start + m_len + endOfLineAdjustmentForCSSLineBreak);
163 bool end = (state != RenderObject::SelectionStart && endPos > m_start && endPos <= lastSelectable);
165 state = RenderObject::SelectionBoth;
167 state = RenderObject::SelectionStart;
169 state = RenderObject::SelectionEnd;
170 else if ((state == RenderObject::SelectionEnd || startPos < m_start) &&
171 (state == RenderObject::SelectionStart || endPos > lastSelectable))
172 state = RenderObject::SelectionInside;
173 else if (state == RenderObject::SelectionBoth)
174 state = RenderObject::SelectionNone;
177 // If there are ellipsis following, make sure their selection is updated.
178 if (m_truncation != cNoTruncation && root().ellipsisBox()) {
179 EllipsisBox* ellipsis = root().ellipsisBox();
180 if (state != RenderObject::SelectionNone) {
182 selectionStartEnd(start, end);
183 // The ellipsis should be considered to be selected if the end of
184 // the selection is past the beginning of the truncation and the
185 // beginning of the selection is before or at the beginning of the
187 ellipsis->setSelectionState(end >= m_truncation && start <= m_truncation ?
188 RenderObject::SelectionInside : RenderObject::SelectionNone);
190 ellipsis->setSelectionState(RenderObject::SelectionNone);
196 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos)
198 int sPos = std::max(startPos - m_start, 0);
199 int ePos = std::min(endPos - m_start, (int)m_len);
204 FontCachePurgePreventer fontCachePurgePreventer;
206 LayoutUnit selTop = selectionTop();
207 LayoutUnit selHeight = selectionHeight();
208 RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
209 const Font& font = styleToUse->font();
211 StringBuilder charactersWithHyphen;
212 bool respectHyphen = ePos == m_len && hasHyphen();
213 TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
215 FloatPoint startingPoint = FloatPoint(logicalLeft(), selTop.toFloat());
217 if (sPos || ePos != static_cast<int>(m_len))
218 r = enclosingIntRect(font.selectionRectForText(textRun, startingPoint, selHeight, sPos, ePos));
219 else // Avoid computing the font width when the entire line box is selected as an optimization.
220 r = enclosingIntRect(FloatRect(startingPoint, FloatSize(m_logicalWidth, selHeight.toFloat())));
222 LayoutUnit logicalWidth = r.width();
223 if (r.x() > logicalRight())
225 else if (r.maxX() > logicalRight())
226 logicalWidth = logicalRight() - r.x();
228 LayoutPoint topPoint = isHorizontal() ? LayoutPoint(r.x(), selTop) : LayoutPoint(selTop, r.x());
229 LayoutUnit width = isHorizontal() ? logicalWidth : selHeight;
230 LayoutUnit height = isHorizontal() ? selHeight : logicalWidth;
232 return LayoutRect(topPoint, LayoutSize(width, height));
235 void InlineTextBox::deleteLine()
237 renderer().removeTextBox(this);
241 void InlineTextBox::extractLine()
246 renderer().extractTextBox(this);
249 void InlineTextBox::attachLine()
254 renderer().attachTextBox(this);
257 float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, float visibleRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
260 m_truncation = cFullTruncation;
264 // For LTR this is the left edge of the box, for RTL, the right edge in parent coordinates.
265 float ellipsisX = flowIsLTR ? visibleRightEdge - ellipsisWidth : visibleLeftEdge + ellipsisWidth;
267 // Criteria for full truncation:
268 // LTR: the left edge of the ellipsis is to the left of our text run.
269 // RTL: the right edge of the ellipsis is to the right of our text run.
270 bool ltrFullTruncation = flowIsLTR && ellipsisX <= logicalLeft();
271 bool rtlFullTruncation = !flowIsLTR && ellipsisX >= logicalLeft() + logicalWidth();
272 if (ltrFullTruncation || rtlFullTruncation) {
273 // Too far. Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
274 m_truncation = cFullTruncation;
279 bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < logicalRight());
280 bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > logicalLeft());
281 if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
284 // The inline box may have different directionality than it's parent. Since truncation
285 // behavior depends both on both the parent and the inline block's directionality, we
286 // must keep track of these separately.
287 bool ltr = isLeftToRightDirection();
288 if (ltr != flowIsLTR) {
289 // Width in pixels of the visible portion of the box, excluding the ellipsis.
290 int visibleBoxWidth = visibleRightEdge - visibleLeftEdge - ellipsisWidth;
291 ellipsisX = ltr ? logicalLeft() + visibleBoxWidth : logicalRight() - visibleBoxWidth;
294 int offset = offsetForPosition(ellipsisX, false);
296 // No characters should be rendered. Set ourselves to full truncation and place the ellipsis at the min of our start
297 // and the ellipsis edge.
298 m_truncation = cFullTruncation;
299 truncatedWidth += ellipsisWidth;
300 return std::min(ellipsisX, logicalLeft());
303 // Set the truncation index on the text run.
304 m_truncation = offset;
306 // If we got here that means that we were only partially truncated and we need to return the pixel offset at which
307 // to place the ellipsis.
308 float widthOfVisibleText = renderer().width(m_start, offset, textPos(), flowIsLTR ? LTR : RTL, isFirstLineStyle());
310 // The ellipsis needs to be placed just after the last visible character.
311 // Where "after" is defined by the flow directionality, not the inline
312 // box directionality.
313 // e.g. In the case of an LTR inline box truncated in an RTL flow then we can
314 // have a situation such as |Hello| -> |...He|
315 truncatedWidth += widthOfVisibleText + ellipsisWidth;
317 return logicalLeft() + widthOfVisibleText;
319 return logicalRight() - widthOfVisibleText - ellipsisWidth;
321 truncatedWidth += logicalWidth();
325 static Color textColorForWhiteBackground(Color textColor)
327 int distanceFromWhite = differenceSquared(textColor, Color::white);
328 // semi-arbitrarily chose 65025 (255^2) value here after a few tests;
329 return distanceFromWhite > 65025 ? textColor : textColor.dark();
332 static void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness)
334 TextDrawingModeFlags mode = context->textDrawingMode();
335 if (strokeThickness > 0) {
336 TextDrawingModeFlags newMode = mode | TextModeStroke;
337 if (mode != newMode) {
338 context->setTextDrawingMode(newMode);
343 if (mode & TextModeFill && fillColor != context->fillColor())
344 context->setFillColor(fillColor);
346 if (mode & TextModeStroke) {
347 if (strokeColor != context->strokeColor())
348 context->setStrokeColor(strokeColor);
349 if (strokeThickness != context->strokeThickness())
350 context->setStrokeThickness(strokeThickness);
354 bool InlineTextBox::isLineBreak() const
356 return renderer().isBR() || (renderer().style()->preserveNewline() && len() == 1 && (*renderer().text().impl())[start()] == '\n');
359 bool InlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
364 FloatPoint boxOrigin = locationIncludingFlipping();
365 boxOrigin.moveBy(accumulatedOffset);
366 FloatRect rect(boxOrigin, size());
367 if (m_truncation != cFullTruncation && visibleToHitTestRequest(request) && locationInContainer.intersects(rect)) {
368 renderer().updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - toLayoutSize(accumulatedOffset)));
369 if (!result.addNodeToRectBasedTestResult(renderer().node(), request, locationInContainer, rect))
375 static void paintTextWithShadows(GraphicsContext* context,
376 const Font& font, const TextRun& textRun,
377 const AtomicString& emphasisMark, int emphasisMarkOffset,
378 int startOffset, int endOffset, int truncationPoint,
379 const FloatPoint& textOrigin, const FloatRect& boxRect,
380 const ShadowList* shadowList, bool horizontal)
382 // Text shadows are disabled when printing. http://crbug.com/258321
383 bool hasShadow = shadowList && !context->printing();
385 context->setDrawLooper(shadowList->createDrawLooper(DrawLooperBuilder::ShadowIgnoresAlpha, horizontal));
387 TextRunPaintInfo textRunPaintInfo(textRun);
388 textRunPaintInfo.bounds = boxRect;
389 if (startOffset <= endOffset) {
390 textRunPaintInfo.from = startOffset;
391 textRunPaintInfo.to = endOffset;
392 if (emphasisMark.isEmpty())
393 context->drawText(font, textRunPaintInfo, textOrigin);
395 context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
398 textRunPaintInfo.from = 0;
399 textRunPaintInfo.to = endOffset;
400 if (emphasisMark.isEmpty())
401 context->drawText(font, textRunPaintInfo, textOrigin);
403 context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
405 if (startOffset < truncationPoint) {
406 textRunPaintInfo.from = startOffset;
407 textRunPaintInfo.to = truncationPoint;
408 if (emphasisMark.isEmpty())
409 context->drawText(font, textRunPaintInfo, textOrigin);
411 context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
416 context->clearDrawLooper();
419 static void paintEmphasisMark(GraphicsContext* context,
420 const AtomicString& emphasisMark, int emphasisMarkOffset,
421 int startOffset, int endOffset, int paintRunLength,
422 const Font& font, Color emphasisMarkColor, Color textStrokeColor, float textStrokeWidth, const ShadowList* textShadow,
423 RenderCombineText* combinedText, const TextRun& textRun,
424 const FloatPoint& textOrigin, const FloatRect& boxRect, bool horizontal)
426 ASSERT(!emphasisMark.isEmpty());
427 updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth);
430 DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
431 FloatPoint emphasisMarkTextOrigin(boxRect.x() + boxRect.width() / 2, boxRect.y() + font.fontMetrics().ascent());
432 context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Clockwise));
433 paintTextWithShadows(context, combinedText->originalFont(), objectReplacementCharacterTextRun, emphasisMark, emphasisMarkOffset, 0, 1, 1, emphasisMarkTextOrigin, boxRect, textShadow, horizontal);
434 context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Counterclockwise));
436 paintTextWithShadows(context, font, textRun, emphasisMark, emphasisMarkOffset, startOffset, endOffset, paintRunLength, textOrigin, boxRect, textShadow, horizontal);
440 bool InlineTextBox::getEmphasisMarkPosition(RenderStyle* style, TextEmphasisPosition& emphasisPosition) const
442 // This function returns true if there are text emphasis marks and they are suppressed by ruby text.
443 if (style->textEmphasisMark() == TextEmphasisMarkNone)
446 emphasisPosition = style->textEmphasisPosition();
447 if (emphasisPosition == TextEmphasisPositionUnder)
448 return true; // Ruby text is always over, so it cannot suppress emphasis marks under.
450 RenderBlock* containingBlock = renderer().containingBlock();
451 if (!containingBlock->isRubyBase())
452 return true; // This text is not inside a ruby base, so it does not have ruby text over it.
454 if (!containingBlock->parent()->isRubyRun())
455 return true; // Cannot get the ruby text.
457 RenderRubyText* rubyText = toRenderRubyRun(containingBlock->parent())->rubyText();
459 // The emphasis marks over are suppressed only if there is a ruby text box and it not empty.
460 return !rubyText || !rubyText->firstLineBox();
465 struct TextPaintingStyle {
468 Color emphasisMarkColor;
470 const ShadowList* shadow;
472 bool operator==(const TextPaintingStyle& other)
474 return fillColor == other.fillColor
475 && strokeColor == other.strokeColor
476 && emphasisMarkColor == other.emphasisMarkColor
477 && strokeWidth == other.strokeWidth
478 && shadow == other.shadow;
480 bool operator!=(const TextPaintingStyle& other) { return !(*this == other); }
483 TextPaintingStyle textPaintingStyle(RenderText& renderer, RenderStyle* style, bool forceBlackText, bool isPrinting)
485 TextPaintingStyle textStyle;
487 if (forceBlackText) {
488 textStyle.fillColor = Color::black;
489 textStyle.strokeColor = Color::black;
490 textStyle.emphasisMarkColor = Color::black;
491 textStyle.strokeWidth = style->textStrokeWidth();
492 textStyle.shadow = 0;
494 textStyle.fillColor = renderer.resolveColor(style, CSSPropertyWebkitTextFillColor);
495 textStyle.strokeColor = renderer.resolveColor(style, CSSPropertyWebkitTextStrokeColor);
496 textStyle.emphasisMarkColor = renderer.resolveColor(style, CSSPropertyWebkitTextEmphasisColor);
497 textStyle.strokeWidth = style->textStrokeWidth();
498 textStyle.shadow = style->textShadow();
500 // Adjust text color when printing with a white background.
501 bool forceBackgroundToWhite = false;
503 if (style->printColorAdjust() == PrintColorAdjustEconomy)
504 forceBackgroundToWhite = true;
505 if (renderer.document().settings() && renderer.document().settings()->shouldPrintBackgrounds())
506 forceBackgroundToWhite = false;
508 if (forceBackgroundToWhite) {
509 textStyle.fillColor = textColorForWhiteBackground(textStyle.fillColor);
510 textStyle.strokeColor = textColorForWhiteBackground(textStyle.strokeColor);
511 textStyle.emphasisMarkColor = textColorForWhiteBackground(textStyle.emphasisMarkColor);
514 // Text shadows are disabled when printing. http://crbug.com/258321
516 textStyle.shadow = 0;
522 TextPaintingStyle selectionPaintingStyle(RenderText& renderer, bool haveSelection, bool forceBlackText, bool isPrinting, const TextPaintingStyle& textStyle)
524 TextPaintingStyle selectionStyle = textStyle;
527 if (!forceBlackText) {
528 selectionStyle.fillColor = renderer.selectionForegroundColor();
529 selectionStyle.emphasisMarkColor = renderer.selectionEmphasisMarkColor();
532 if (RenderStyle* pseudoStyle = renderer.getCachedPseudoStyle(SELECTION)) {
533 selectionStyle.strokeColor = forceBlackText ? Color::black : renderer.resolveColor(pseudoStyle, CSSPropertyWebkitTextStrokeColor);
534 selectionStyle.strokeWidth = pseudoStyle->textStrokeWidth();
535 selectionStyle.shadow = forceBlackText ? 0 : pseudoStyle->textShadow();
538 // Text shadows are disabled when printing. http://crbug.com/258321
540 selectionStyle.shadow = 0;
543 return selectionStyle;
548 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
550 if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(&renderer()) || renderer().style()->visibility() != VISIBLE
551 || m_truncation == cFullTruncation || paintInfo.phase == PaintPhaseOutline || !m_len)
554 ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
556 LayoutRect logicalVisualOverflow = logicalOverflowRect();
557 LayoutUnit logicalStart = logicalVisualOverflow.x() + (isHorizontal() ? paintOffset.x() : paintOffset.y());
558 LayoutUnit logicalExtent = logicalVisualOverflow.width();
560 LayoutUnit paintEnd = isHorizontal() ? paintInfo.rect.maxX() : paintInfo.rect.maxY();
561 LayoutUnit paintStart = isHorizontal() ? paintInfo.rect.x() : paintInfo.rect.y();
563 // When subpixel font scaling is enabled text runs are positioned at
564 // subpixel boundaries on the x-axis and thus there is no reason to
565 // snap the x value. We still round the y-axis to ensure consistent
567 LayoutPoint adjustedPaintOffset = RuntimeEnabledFeatures::subpixelFontScalingEnabled()
568 ? LayoutPoint(paintOffset.x(), paintOffset.y().round())
569 : roundedIntPoint(paintOffset);
571 if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
574 bool isPrinting = renderer().document().printing();
576 // Determine whether or not we're selected.
577 bool haveSelection = !isPrinting && paintInfo.phase != PaintPhaseTextClip && selectionState() != RenderObject::SelectionNone;
578 if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
579 // When only painting the selection, don't bother to paint if there is none.
582 if (m_truncation != cNoTruncation) {
583 if (renderer().containingBlock()->style()->isLeftToRightDirection() != isLeftToRightDirection()) {
584 // Make the visible fragment of text hug the edge closest to the rest of the run by moving the origin
585 // at which we start drawing text.
586 // e.g. In the case of LTR text truncated in an RTL Context, the correct behavior is:
587 // |Hello|CBA| -> |...He|CBA|
588 // In order to draw the fragment "He" aligned to the right edge of it's box, we need to start drawing
589 // farther to the right.
590 // NOTE: WebKit's behavior differs from that of IE which appears to just overlay the ellipsis on top of the
591 // truncated string i.e. |Hello|CBA| -> |...lo|CBA|
592 LayoutUnit widthOfVisibleText = renderer().width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
593 LayoutUnit widthOfHiddenText = m_logicalWidth - widthOfVisibleText;
594 // FIXME: The hit testing logic also needs to take this translation into account.
595 LayoutSize truncationOffset(isLeftToRightDirection() ? widthOfHiddenText : -widthOfHiddenText, 0);
596 adjustedPaintOffset.move(isHorizontal() ? truncationOffset : truncationOffset.transposedSize());
600 GraphicsContext* context = paintInfo.context;
601 RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
603 adjustedPaintOffset.move(0, styleToUse->isHorizontalWritingMode() ? 0 : -logicalHeight());
605 FloatPoint boxOrigin = locationIncludingFlipping();
606 boxOrigin.move(adjustedPaintOffset.x().toFloat(), adjustedPaintOffset.y().toFloat());
607 FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
609 RenderCombineText* combinedText = styleToUse->hasTextCombine() && renderer().isCombineText() && toRenderCombineText(renderer()).isCombined() ? &toRenderCombineText(renderer()) : 0;
611 bool shouldRotate = !isHorizontal() && !combinedText;
613 context->concatCTM(rotation(boxRect, Clockwise));
615 // Determine whether or not we have composition underlines to draw.
616 bool containsComposition = renderer().node() && renderer().frame()->inputMethodController().compositionNode() == renderer().node();
617 bool useCustomUnderlines = containsComposition && renderer().frame()->inputMethodController().compositionUsesCustomUnderlines();
619 // Determine text colors.
620 TextPaintingStyle textStyle = textPaintingStyle(renderer(), styleToUse, paintInfo.forceBlackText(), isPrinting);
621 TextPaintingStyle selectionStyle = selectionPaintingStyle(renderer(), haveSelection, paintInfo.forceBlackText(), isPrinting, textStyle);
622 bool paintSelectedTextOnly = (paintInfo.phase == PaintPhaseSelection);
623 bool paintSelectedTextSeparately = !paintSelectedTextOnly && textStyle != selectionStyle;
626 const Font& font = styleToUse->font();
628 FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
630 combinedText->adjustTextOrigin(textOrigin, boxRect);
632 // 1. Paint backgrounds behind text if needed. Examples of such backgrounds include selection
633 // and composition highlights.
634 if (paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseTextClip && !isPrinting) {
635 if (containsComposition) {
636 paintCompositionBackgrounds(context, boxOrigin, styleToUse, font, useCustomUnderlines);
639 paintDocumentMarkers(context, boxOrigin, styleToUse, font, true);
641 if (haveSelection && !useCustomUnderlines)
642 paintSelection(context, boxOrigin, styleToUse, font, selectionStyle.fillColor);
645 // 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
650 string = renderer().text().createView();
651 if (static_cast<unsigned>(length) != string.length() || m_start)
652 string.narrow(m_start, length);
653 maximumLength = renderer().textLength() - m_start;
655 combinedText->getStringToRender(m_start, string, length);
656 maximumLength = length;
659 StringBuilder charactersWithHyphen;
660 TextRun textRun = constructTextRun(styleToUse, font, string, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
662 length = textRun.length();
666 if (paintSelectedTextOnly || paintSelectedTextSeparately)
667 selectionStartEnd(sPos, ePos);
669 if (m_truncation != cNoTruncation) {
670 sPos = std::min<int>(sPos, m_truncation);
671 ePos = std::min<int>(ePos, m_truncation);
672 length = m_truncation;
675 int emphasisMarkOffset = 0;
676 TextEmphasisPosition emphasisMarkPosition;
677 bool hasTextEmphasis = getEmphasisMarkPosition(styleToUse, emphasisMarkPosition);
678 const AtomicString& emphasisMark = hasTextEmphasis ? styleToUse->textEmphasisMarkString() : nullAtom;
679 if (!emphasisMark.isEmpty())
680 emphasisMarkOffset = emphasisMarkPosition == TextEmphasisPositionOver ? -font.fontMetrics().ascent() - font.emphasisMarkDescent(emphasisMark) : font.fontMetrics().descent() + font.emphasisMarkAscent(emphasisMark);
682 if (!paintSelectedTextOnly) {
683 // FIXME: Truncate right-to-left text correctly.
685 int endOffset = length;
686 if (paintSelectedTextSeparately && ePos > sPos) {
691 // For stroked painting, we have to change the text drawing mode. It's probably dangerous to leave that mutated as a side
692 // effect, so only when we know we're stroking, do a save/restore.
693 GraphicsContextStateSaver stateSaver(*context, textStyle.strokeWidth > 0);
695 updateGraphicsContext(context, textStyle.fillColor, textStyle.strokeColor, textStyle.strokeWidth);
696 paintTextWithShadows(context, font, textRun, nullAtom, 0, startOffset, endOffset, length, textOrigin, boxRect, textStyle.shadow, isHorizontal());
698 if (!emphasisMark.isEmpty())
699 paintEmphasisMark(context, emphasisMark, emphasisMarkOffset, startOffset, endOffset, length, font, textStyle.emphasisMarkColor, textStyle.strokeColor, textStyle.strokeWidth, textStyle.shadow, combinedText, textRun, textOrigin, boxRect, isHorizontal());
702 if ((paintSelectedTextOnly || paintSelectedTextSeparately) && sPos < ePos) {
703 // paint only the text that is selected
704 GraphicsContextStateSaver stateSaver(*context, selectionStyle.strokeWidth > 0);
706 updateGraphicsContext(context, selectionStyle.fillColor, selectionStyle.strokeColor, selectionStyle.strokeWidth);
707 paintTextWithShadows(context, font, textRun, nullAtom, 0, sPos, ePos, length, textOrigin, boxRect, selectionStyle.shadow, isHorizontal());
709 if (!emphasisMark.isEmpty())
710 paintEmphasisMark(context, emphasisMark, emphasisMarkOffset, sPos, ePos, length, font, selectionStyle.emphasisMarkColor, selectionStyle.strokeColor, textStyle.strokeWidth, selectionStyle.shadow, combinedText, textRun, textOrigin, boxRect, isHorizontal());
714 TextDecoration textDecorations = styleToUse->textDecorationsInEffect();
715 if (textDecorations != TextDecorationNone && paintInfo.phase != PaintPhaseSelection) {
716 updateGraphicsContext(context, textStyle.fillColor, textStyle.strokeColor, textStyle.strokeWidth);
718 context->concatCTM(rotation(boxRect, Clockwise));
719 paintDecoration(context, boxOrigin, textDecorations, textStyle.shadow);
721 context->concatCTM(rotation(boxRect, Counterclockwise));
724 if (paintInfo.phase == PaintPhaseForeground) {
725 paintDocumentMarkers(context, boxOrigin, styleToUse, font, false);
727 // Paint custom underlines for compositions.
728 if (useCustomUnderlines) {
729 const Vector<CompositionUnderline>& underlines = renderer().frame()->inputMethodController().customCompositionUnderlines();
730 CompositionUnderlineRangeFilter filter(underlines, start(), end());
731 for (CompositionUnderlineRangeFilter::ConstIterator it = filter.begin(); it != filter.end(); ++it) {
732 if (it->color == Color::transparent)
734 paintCompositionUnderline(context, boxOrigin, *it);
740 context->concatCTM(rotation(boxRect, Counterclockwise));
743 void InlineTextBox::selectionStartEnd(int& sPos, int& ePos)
745 int startPos, endPos;
746 if (renderer().selectionState() == RenderObject::SelectionInside) {
748 endPos = renderer().textLength();
750 renderer().selectionStartEnd(startPos, endPos);
751 if (renderer().selectionState() == RenderObject::SelectionStart)
752 endPos = renderer().textLength();
753 else if (renderer().selectionState() == RenderObject::SelectionEnd)
757 sPos = std::max(startPos - m_start, 0);
758 ePos = std::min(endPos - m_start, (int)m_len);
761 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color textColor)
763 // See if we have a selection to paint at all.
765 selectionStartEnd(sPos, ePos);
769 Color c = renderer().selectionBackgroundColor();
773 // If the text color ends up being the same as the selection background, invert the selection
776 c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
778 GraphicsContextStateSaver stateSaver(*context);
779 updateGraphicsContext(context, c, c, 0); // Don't draw text at all!
781 // If the text is truncated, let the thing being painted in the truncation
782 // draw its own highlight.
783 int length = m_truncation != cNoTruncation ? m_truncation : m_len;
784 StringView string = renderer().text().createView();
786 if (string.length() != static_cast<unsigned>(length) || m_start)
787 string.narrow(m_start, length);
789 StringBuilder charactersWithHyphen;
790 bool respectHyphen = ePos == length && hasHyphen();
791 TextRun textRun = constructTextRun(style, font, string, renderer().textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
793 ePos = textRun.length();
795 LayoutUnit selectionBottom = root().selectionBottom();
796 LayoutUnit selectionTop = root().selectionTopAdjustedForPrecedingBlock();
798 int deltaY = roundToInt(renderer().style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
799 int selHeight = std::max(0, roundToInt(selectionBottom - selectionTop));
801 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
802 FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
803 context->clip(clipRect);
805 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, sPos, ePos);
808 unsigned InlineTextBox::underlinePaintStart(const CompositionUnderline& underline)
810 return std::max(static_cast<unsigned>(m_start), underline.startOffset);
813 unsigned InlineTextBox::underlinePaintEnd(const CompositionUnderline& underline)
815 unsigned paintEnd = std::min(end() + 1, underline.endOffset); // end() points at the last char, not past it.
816 if (m_truncation != cNoTruncation)
817 paintEnd = std::min(paintEnd, static_cast<unsigned>(m_start + m_truncation));
821 void InlineTextBox::paintSingleCompositionBackgroundRun(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color backgroundColor, int startPos, int endPos)
823 int sPos = std::max(startPos - m_start, 0);
824 int ePos = std::min(endPos - m_start, static_cast<int>(m_len));
828 GraphicsContextStateSaver stateSaver(*context);
830 updateGraphicsContext(context, backgroundColor, backgroundColor, 0); // Don't draw text at all!
832 int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
833 int selHeight = selectionHeight();
834 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
835 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, backgroundColor, sPos, ePos);
838 static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorationStyle)
840 StrokeStyle strokeStyle = SolidStroke;
841 switch (decorationStyle) {
842 case TextDecorationStyleSolid:
843 strokeStyle = SolidStroke;
845 case TextDecorationStyleDouble:
846 strokeStyle = DoubleStroke;
848 case TextDecorationStyleDotted:
849 strokeStyle = DottedStroke;
851 case TextDecorationStyleDashed:
852 strokeStyle = DashedStroke;
854 case TextDecorationStyleWavy:
855 strokeStyle = WavyStroke;
862 static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const float textDecorationThickness)
864 // Compute the gap between the font and the underline. Use at least one
865 // pixel gap, if underline is thick then use a bigger gap.
868 // Underline position of zero means draw underline on Baseline Position,
869 // in Blink we need at least 1-pixel gap to adding following check.
870 // Positive underline Position means underline should be drawn above baselin e
871 // and negative value means drawing below baseline, negating the value as in Blink
872 // downward Y-increases.
874 if (fontMetrics.underlinePosition())
875 gap = -fontMetrics.underlinePosition();
877 gap = std::max<int>(1, ceilf(textDecorationThickness / 2.f));
879 // FIXME: We support only horizontal text for now.
880 switch (underlinePosition) {
881 case TextUnderlinePositionAuto:
882 return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
883 case TextUnderlinePositionUnder: {
884 // Position underline relative to the under edge of the lowest element's content box.
885 const float offset = inlineTextBox->root().maxLogicalTop() - inlineTextBox->logicalTop();
887 return inlineTextBox->logicalHeight() + gap + offset;
888 return inlineTextBox->logicalHeight() + gap;
892 ASSERT_NOT_REACHED();
893 return fontMetrics.ascent() + gap;
896 static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
903 unsigned stepCount = static_cast<unsigned>(length / step);
905 // Each Bezier curve starts at the same pixel that the previous one
906 // ended. We need to subtract (stepCount - 1) pixels when calculating the
907 // length covered to account for that.
908 float uncoveredLength = length - (stepCount * step - (stepCount - 1));
909 float adjustment = uncoveredLength / stepCount;
911 controlPointDistance += adjustment;
915 * Draw one cubic Bezier curve and repeat the same pattern long the the decoration's axis.
916 * The start point (p1), controlPoint1, controlPoint2 and end point (p2) of the Bezier curve
917 * form a diamond shape:
929 * (x1, y1) p1 + . + p2 (x2, y2) - <--- Decoration's axis
932 * . . | controlPointDistance
941 static void strokeWavyTextDecoration(GraphicsContext* context, FloatPoint p1, FloatPoint p2, float strokeThickness)
943 context->adjustLineToPixelBoundaries(p1, p2, strokeThickness, context->strokeStyle());
948 // Distance between decoration's axis and Bezier curve's control points.
949 // The height of the curve is based on this distance. Use a minimum of 6 pixels distance since
950 // the actual curve passes approximately at half of that distance, that is 3 pixels.
951 // The minimum height of the curve is also approximately 3 pixels. Increases the curve's height
952 // as strockThickness increases to make the curve looks better.
953 float controlPointDistance = 3 * std::max<float>(2, strokeThickness);
955 // Increment used to form the diamond shape between start point (p1), control
956 // points and end point (p2) along the axis of the decoration. Makes the
957 // curve wider as strockThickness increases to make the curve looks better.
958 float step = 2 * std::max<float>(2, strokeThickness);
960 bool isVerticalLine = (p1.x() == p2.x());
962 if (isVerticalLine) {
963 ASSERT(p1.x() == p2.x());
965 float xAxis = p1.x();
969 if (p1.y() < p2.y()) {
977 adjustStepToDecorationLength(step, controlPointDistance, y2 - y1);
978 FloatPoint controlPoint1(xAxis + controlPointDistance, 0);
979 FloatPoint controlPoint2(xAxis - controlPointDistance, 0);
981 for (float y = y1; y + 2 * step <= y2;) {
982 controlPoint1.setY(y + step);
983 controlPoint2.setY(y + step);
985 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(xAxis, y));
988 ASSERT(p1.y() == p2.y());
990 float yAxis = p1.y();
994 if (p1.x() < p2.x()) {
1002 adjustStepToDecorationLength(step, controlPointDistance, x2 - x1);
1003 FloatPoint controlPoint1(0, yAxis + controlPointDistance);
1004 FloatPoint controlPoint2(0, yAxis - controlPointDistance);
1006 for (float x = x1; x + 2 * step <= x2;) {
1007 controlPoint1.setX(x + step);
1008 controlPoint2.setX(x + step);
1010 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(x, yAxis));
1014 context->setShouldAntialias(true);
1015 context->strokePath(path);
1018 static bool shouldSetDecorationAntialias(TextDecorationStyle decorationStyle)
1020 return decorationStyle == TextDecorationStyleDotted || decorationStyle == TextDecorationStyleDashed;
1023 static bool shouldSetDecorationAntialias(TextDecorationStyle underline, TextDecorationStyle overline, TextDecorationStyle linethrough)
1025 return shouldSetDecorationAntialias(underline) || shouldSetDecorationAntialias(overline) || shouldSetDecorationAntialias(linethrough);
1028 static void paintAppliedDecoration(GraphicsContext* context, FloatPoint start, float width, float doubleOffset, int wavyOffsetFactor,
1029 RenderObject::AppliedTextDecoration decoration, float thickness, bool antialiasDecoration, bool isPrinting)
1031 context->setStrokeStyle(textDecorationStyleToStrokeStyle(decoration.style));
1032 context->setStrokeColor(decoration.color);
1034 switch (decoration.style) {
1035 case TextDecorationStyleWavy:
1036 strokeWavyTextDecoration(context, start + FloatPoint(0, doubleOffset * wavyOffsetFactor), start + FloatPoint(width, doubleOffset * wavyOffsetFactor), thickness);
1038 case TextDecorationStyleDotted:
1039 case TextDecorationStyleDashed:
1040 context->setShouldAntialias(antialiasDecoration);
1043 context->drawLineForText(start, width, isPrinting);
1045 if (decoration.style == TextDecorationStyleDouble)
1046 context->drawLineForText(start + FloatPoint(0, doubleOffset), width, isPrinting);
1050 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, const ShadowList* shadowList)
1052 GraphicsContextStateSaver stateSaver(*context);
1054 if (m_truncation == cFullTruncation)
1057 FloatPoint localOrigin = boxOrigin;
1059 float width = m_logicalWidth;
1060 if (m_truncation != cNoTruncation) {
1061 width = renderer().width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1062 if (!isLeftToRightDirection())
1063 localOrigin.move(m_logicalWidth - width, 0);
1066 // Get the text decoration colors.
1067 RenderObject::AppliedTextDecoration underline, overline, linethrough;
1069 renderer().getTextDecorations(deco, underline, overline, linethrough, true);
1070 if (isFirstLineStyle())
1071 renderer().getTextDecorations(deco, underline, overline, linethrough, true, true);
1073 // Use a special function for underlines to get the positioning exactly right.
1074 bool isPrinting = renderer().document().printing();
1076 bool linesAreOpaque = !isPrinting && (!(deco & TextDecorationUnderline) || underline.color.alpha() == 255) && (!(deco & TextDecorationOverline) || overline.color.alpha() == 255) && (!(deco & TextDecorationLineThrough) || linethrough.color.alpha() == 255);
1078 RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
1079 int baseline = styleToUse->fontMetrics().ascent();
1081 size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
1082 // Set the thick of the line to be 10% (or something else ?)of the computed font size and not less than 1px.
1083 // Using computedFontSize should take care of zoom as well.
1085 // Update Underline thickness, in case we have Faulty Font Metrics calculating underline thickness by old method.
1086 float textDecorationThickness = styleToUse->fontMetrics().underlineThickness();
1087 int fontHeightInt = (int)(styleToUse->fontMetrics().floatHeight() + 0.5);
1088 if ((textDecorationThickness == 0.f) || (textDecorationThickness >= (fontHeightInt >> 1)))
1089 textDecorationThickness = std::max(1.f, styleToUse->computedFontSize() / 10.f);
1091 context->setStrokeThickness(textDecorationThickness);
1093 bool antialiasDecoration = shouldSetDecorationAntialias(overline.style, underline.style, linethrough.style)
1094 && RenderBoxModelObject::shouldAntialiasLines(context);
1096 float extraOffset = 0;
1097 if (!linesAreOpaque && shadowCount > 1) {
1098 FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1099 for (size_t i = shadowCount; i--; ) {
1100 const ShadowData& s = shadowList->shadows()[i];
1101 FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1102 shadowRect.inflate(s.blur());
1103 float shadowX = isHorizontal() ? s.x() : s.y();
1104 float shadowY = isHorizontal() ? s.y() : -s.x();
1105 shadowRect.move(shadowX, shadowY);
1106 clipRect.unite(shadowRect);
1107 extraOffset = std::max(extraOffset, std::max(0.0f, shadowY) + s.blur());
1109 context->clip(clipRect);
1110 extraOffset += baseline + 2;
1111 localOrigin.move(0, extraOffset);
1114 for (size_t i = std::max(static_cast<size_t>(1), shadowCount); i--; ) {
1115 // Even if we have no shadows, we still want to run the code below this once.
1116 if (i < shadowCount) {
1118 // The last set of lines paints normally inside the clip.
1119 localOrigin.move(0, -extraOffset);
1122 const ShadowData& shadow = shadowList->shadows()[i];
1123 float shadowX = isHorizontal() ? shadow.x() : shadow.y();
1124 float shadowY = isHorizontal() ? shadow.y() : -shadow.x();
1125 context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow.blur(), shadow.color());
1128 // Offset between lines - always non-zero, so lines never cross each other.
1129 float doubleOffset = textDecorationThickness + 1.f;
1131 if (deco & TextDecorationUnderline) {
1132 const int underlineOffset = computeUnderlineOffset(styleToUse->textUnderlinePosition(), styleToUse->fontMetrics(), this, textDecorationThickness);
1133 paintAppliedDecoration(context, localOrigin + FloatPoint(0, underlineOffset), width, doubleOffset, 1, underline, textDecorationThickness, antialiasDecoration, isPrinting);
1135 if (deco & TextDecorationOverline) {
1136 paintAppliedDecoration(context, localOrigin, width, -doubleOffset, 1, overline, textDecorationThickness, antialiasDecoration, isPrinting);
1138 if (deco & TextDecorationLineThrough) {
1139 const float lineThroughOffset = 2 * baseline / 3;
1140 paintAppliedDecoration(context, localOrigin + FloatPoint(0, lineThroughOffset), width, doubleOffset, 0, linethrough, textDecorationThickness, antialiasDecoration, isPrinting);
1145 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1147 switch (markerType) {
1148 case DocumentMarker::Spelling:
1149 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1150 case DocumentMarker::Grammar:
1151 return GraphicsContext::DocumentMarkerGrammarLineStyle;
1153 ASSERT_NOT_REACHED();
1154 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1158 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1160 // Never print spelling/grammar markers (5327887)
1161 if (renderer().document().printing())
1164 if (m_truncation == cFullTruncation)
1167 float start = 0; // start of line to draw, relative to tx
1168 float width = m_logicalWidth; // how much line to draw
1170 // Determine whether we need to measure text
1171 bool markerSpansWholeBox = true;
1172 if (m_start <= (int)marker->startOffset())
1173 markerSpansWholeBox = false;
1174 if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1175 markerSpansWholeBox = false;
1176 if (m_truncation != cNoTruncation)
1177 markerSpansWholeBox = false;
1179 if (!markerSpansWholeBox || grammar) {
1180 int startPosition = std::max<int>(marker->startOffset() - m_start, 0);
1181 int endPosition = std::min<int>(marker->endOffset() - m_start, m_len);
1183 if (m_truncation != cNoTruncation)
1184 endPosition = std::min<int>(endPosition, m_truncation);
1186 // Calculate start & width
1187 int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1188 int selHeight = selectionHeight();
1189 FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1190 TextRun run = constructTextRun(style, font);
1192 // FIXME: Convert the document markers to float rects.
1193 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1194 start = markerRect.x() - startPoint.x();
1195 width = markerRect.width();
1197 // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1198 // display a toolTip. We don't do this for misspelling markers.
1200 markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1201 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1202 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1206 // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1207 // make sure to fit within those bounds. This means the top pixel(s) of the underline will overlap the
1208 // bottom pixel(s) of the glyphs in smaller font sizes. The alternatives are to increase the line spacing (bad!!)
1209 // or decrease the underline thickness. The overlap is actually the most useful, and matches what AppKit does.
1210 // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1211 // we pin to two pixels under the baseline.
1212 int lineThickness = misspellingLineThickness;
1213 int baseline = renderer().style(isFirstLineStyle())->fontMetrics().ascent();
1214 int descent = logicalHeight() - baseline;
1215 int underlineOffset;
1216 if (descent <= (2 + lineThickness)) {
1217 // Place the underline at the very bottom of the text in small/medium fonts.
1218 underlineOffset = logicalHeight() - lineThickness;
1220 // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1221 underlineOffset = baseline + 2;
1223 pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1226 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1228 // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1229 // the same word there are no pieces sticking out.
1230 int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1231 int selHeight = selectionHeight();
1233 int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1234 int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1235 TextRun run = constructTextRun(style, font);
1237 // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1238 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1239 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1240 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1242 // Optionally highlight the text
1243 if (renderer().frame()->editor().markedTextMatchesAreHighlighted()) {
1244 Color color = marker->activeMatch() ?
1245 RenderTheme::theme().platformActiveTextSearchHighlightColor() :
1246 RenderTheme::theme().platformInactiveTextSearchHighlightColor();
1247 GraphicsContextStateSaver stateSaver(*pt);
1248 updateGraphicsContext(pt, color, color, 0); // Don't draw text at all!
1249 pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1250 pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, sPos, ePos);
1254 void InlineTextBox::paintCompositionBackgrounds(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool useCustomUnderlines)
1256 if (useCustomUnderlines) {
1257 // Paint custom background highlights for compositions.
1258 const Vector<CompositionUnderline>& underlines = renderer().frame()->inputMethodController().customCompositionUnderlines();
1259 CompositionUnderlineRangeFilter filter(underlines, start(), end());
1260 for (CompositionUnderlineRangeFilter::ConstIterator it = filter.begin(); it != filter.end(); ++it) {
1261 if (it->backgroundColor == Color::transparent)
1263 paintSingleCompositionBackgroundRun(pt, boxOrigin, style, font, it->backgroundColor, underlinePaintStart(*it), underlinePaintEnd(*it));
1267 paintSingleCompositionBackgroundRun(pt, boxOrigin, style, font, RenderTheme::theme().platformDefaultCompositionBackgroundColor(),
1268 renderer().frame()->inputMethodController().compositionStart(),
1269 renderer().frame()->inputMethodController().compositionEnd());
1273 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1275 if (!renderer().node())
1278 DocumentMarkerVector markers = renderer().document().markers().markersFor(renderer().node());
1279 DocumentMarkerVector::const_iterator markerIt = markers.begin();
1281 // Give any document markers that touch this run a chance to draw before the text has been drawn.
1282 // Note end() points at the last char, not one past it like endOffset and ranges do.
1283 for ( ; markerIt != markers.end(); ++markerIt) {
1284 DocumentMarker* marker = *markerIt;
1286 // Paint either the background markers or the foreground markers, but not both
1287 switch (marker->type()) {
1288 case DocumentMarker::Grammar:
1289 case DocumentMarker::Spelling:
1293 case DocumentMarker::TextMatch:
1301 if (marker->endOffset() <= start())
1302 // marker is completely before this run. This might be a marker that sits before the
1303 // first run we draw, or markers that were within runs we skipped due to truncation.
1306 if (marker->startOffset() > end())
1307 // marker is completely after this run, bail. A later run will paint it.
1310 // marker intersects this run. Paint it.
1311 switch (marker->type()) {
1312 case DocumentMarker::Spelling:
1313 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1315 case DocumentMarker::Grammar:
1316 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1318 case DocumentMarker::TextMatch:
1319 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1322 ASSERT_NOT_REACHED();
1328 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1330 if (m_truncation == cFullTruncation)
1333 unsigned paintStart = underlinePaintStart(underline);
1334 unsigned paintEnd = underlinePaintEnd(underline);
1336 // start of line to draw, relative to paintOffset.
1337 float start = paintStart == static_cast<unsigned>(m_start) ? 0 :
1338 renderer().width(m_start, paintStart - m_start, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1339 // how much line to draw
1340 float width = (paintStart == static_cast<unsigned>(m_start) && paintEnd == static_cast<unsigned>(end()) + 1) ? m_logicalWidth :
1341 renderer().width(paintStart, paintEnd - paintStart, textPos() + start, isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1343 // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1344 // All other marked text underlines are 1px thick.
1345 // If there's not enough space the underline will touch or overlap characters.
1346 int lineThickness = 1;
1347 int baseline = renderer().style(isFirstLineStyle())->fontMetrics().ascent();
1348 if (underline.thick && logicalHeight() - baseline >= 2)
1351 // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1352 // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1356 ctx->setStrokeColor(underline.color);
1357 ctx->setStrokeThickness(lineThickness);
1358 ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, renderer().document().printing());
1361 int InlineTextBox::caretMinOffset() const
1366 int InlineTextBox::caretMaxOffset() const
1368 return m_start + m_len;
1371 float InlineTextBox::textPos() const
1373 // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1374 // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1375 if (logicalLeft() == 0)
1377 return logicalLeft() - root().logicalLeft();
1380 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1385 if (lineOffset - logicalLeft() > logicalWidth())
1386 return isLeftToRightDirection() ? len() : 0;
1387 if (lineOffset - logicalLeft() < 0)
1388 return isLeftToRightDirection() ? 0 : len();
1390 FontCachePurgePreventer fontCachePurgePreventer;
1392 RenderText& text = renderer();
1393 RenderStyle* style = text.style(isFirstLineStyle());
1394 const Font& font = style->font();
1395 return font.offsetForPosition(constructTextRun(style, font), lineOffset - logicalLeft(), includePartialGlyphs);
1398 float InlineTextBox::positionForOffset(int offset) const
1400 ASSERT(offset >= m_start);
1401 ASSERT(offset <= m_start + m_len);
1404 return logicalLeft();
1406 FontCachePurgePreventer fontCachePurgePreventer;
1408 RenderText& text = renderer();
1409 RenderStyle* styleToUse = text.style(isFirstLineStyle());
1411 const Font& font = styleToUse->font();
1412 int from = !isLeftToRightDirection() ? offset - m_start : 0;
1413 int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1414 // FIXME: Do we need to add rightBearing here?
1415 return font.selectionRectForText(constructTextRun(styleToUse, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1418 bool InlineTextBox::containsCaretOffset(int offset) const
1420 // Offsets before the box are never "in".
1421 if (offset < m_start)
1424 int pastEnd = m_start + m_len;
1426 // Offsets inside the box (not at either edge) are always "in".
1427 if (offset < pastEnd)
1430 // Offsets outside the box are always "out".
1431 if (offset > pastEnd)
1434 // Offsets at the end are "out" for line breaks (they are on the next line).
1438 // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1442 void InlineTextBox::characterWidths(Vector<float>& widths) const
1444 FontCachePurgePreventer fontCachePurgePreventer;
1446 RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
1447 const Font& font = styleToUse->font();
1449 TextRun textRun = constructTextRun(styleToUse, font);
1451 GlyphBuffer glyphBuffer;
1452 WidthIterator it(&font, textRun);
1453 float lastWidth = 0;
1454 widths.resize(m_len);
1455 for (unsigned i = 0; i < m_len; i++) {
1456 it.advance(i + 1, &glyphBuffer);
1457 widths[i] = it.m_runWidthSoFar - lastWidth;
1458 lastWidth = it.m_runWidthSoFar;
1462 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringBuilder* charactersWithHyphen) const
1465 ASSERT(renderer().text());
1467 StringView string = renderer().text().createView();
1468 unsigned startPos = start();
1469 unsigned length = len();
1471 if (string.length() != length || startPos)
1472 string.narrow(startPos, length);
1474 return constructTextRun(style, font, string, renderer().textLength() - startPos, charactersWithHyphen);
1477 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringView string, int maximumLength, StringBuilder* charactersWithHyphen) const
1481 if (charactersWithHyphen) {
1482 const AtomicString& hyphenString = style->hyphenString();
1483 charactersWithHyphen->reserveCapacity(string.length() + hyphenString.length());
1484 charactersWithHyphen->append(string);
1485 charactersWithHyphen->append(hyphenString);
1486 string = charactersWithHyphen->toString().createView();
1487 maximumLength = string.length();
1490 ASSERT(maximumLength >= static_cast<int>(string.length()));
1492 TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !renderer().canUseSimpleFontCodePath());
1493 run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
1494 run.setCharacterScanForCodePath(!renderer().canUseSimpleFontCodePath());
1495 if (textRunNeedsRenderingContext(font))
1496 run.setRenderingContext(SVGTextRunRenderingContext::create(&renderer()));
1498 // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1499 run.setCharactersLength(maximumLength);
1500 ASSERT(run.charactersLength() >= run.length());
1504 TextRun InlineTextBox::constructTextRunForInspector(RenderStyle* style, const Font& font) const
1506 return InlineTextBox::constructTextRun(style, font);
1511 const char* InlineTextBox::boxName() const
1513 return "InlineTextBox";
1516 void InlineTextBox::showBox(int printedCharacters) const
1518 const RenderText& obj = renderer();
1519 String value = obj.text();
1520 value = value.substring(start(), len());
1521 value.replaceWithLiteral('\\', "\\\\");
1522 value.replaceWithLiteral('\n', "\\n");
1523 printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1524 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1526 printedCharacters = fprintf(stderr, "\t%s %p", obj.renderName(), &obj);
1527 const int rendererCharacterOffset = 24;
1528 for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1530 fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1535 } // namespace blink