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 "InlineTextBox.h"
27 #include "ChromeClient.h"
28 #include "DashArray.h"
30 #include "DocumentMarkerController.h"
32 #include "EllipsisBox.h"
33 #include "FontCache.h"
35 #include "GraphicsContext.h"
36 #include "HitTestResult.h"
37 #include "ImageBuffer.h"
39 #include "PaintInfo.h"
40 #include "RenderedDocumentMarker.h"
41 #include "RenderBlock.h"
42 #include "RenderCombineText.h"
43 #include "RenderLineBreak.h"
44 #include "RenderRubyRun.h"
45 #include "RenderRubyText.h"
46 #include "RenderTheme.h"
47 #include "RenderView.h"
49 #include "SVGTextRunRenderingContext.h"
51 #include "TextPaintStyle.h"
52 #include "TextPainter.h"
53 #include "break_lines.h"
55 #include <wtf/text/CString.h>
59 struct SameSizeAsInlineTextBox : public InlineBox {
60 unsigned variables[1];
61 unsigned short variables2[2];
65 COMPILE_ASSERT(sizeof(InlineTextBox) == sizeof(SameSizeAsInlineTextBox), InlineTextBox_should_stay_small);
67 typedef WTF::HashMap<const InlineTextBox*, LayoutRect> InlineTextBoxOverflowMap;
68 static InlineTextBoxOverflowMap* gTextBoxesWithOverflow;
70 #if ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
71 static bool compareTuples(std::pair<float, float> l, std::pair<float, float> r)
73 return l.first < r.first;
76 static DashArray translateIntersectionPointsToSkipInkBoundaries(const DashArray& intersections, float dilationAmount, float totalWidth)
78 ASSERT(!(intersections.size() % 2));
80 // Step 1: Make pairs so we can sort based on range starting-point. We dilate the ranges in this step as well.
81 Vector<std::pair<float, float>> tuples;
82 for (auto i = intersections.begin(); i != intersections.end(); i++, i++)
83 tuples.append(std::make_pair(*i - dilationAmount, *(i + 1) + dilationAmount));
84 std::sort(tuples.begin(), tuples.end(), &compareTuples);
86 // Step 2: Deal with intersecting ranges.
87 Vector<std::pair<float, float>> intermediateTuples;
88 if (tuples.size() >= 2) {
89 intermediateTuples.append(*tuples.begin());
90 for (auto i = tuples.begin() + 1; i != tuples.end(); i++) {
91 float& firstEnd = intermediateTuples.last().second;
92 float secondStart = i->first;
93 float secondEnd = i->second;
94 if (secondStart <= firstEnd && secondEnd <= firstEnd) {
95 // Ignore this range completely
96 } else if (secondStart <= firstEnd)
99 intermediateTuples.append(*i);
102 intermediateTuples = tuples;
104 // Step 3: Output the space between the ranges, but only if the space warrants an underline.
107 for (const auto& tuple : intermediateTuples) {
108 if (tuple.first - previous > dilationAmount) {
109 result.append(previous);
110 result.append(tuple.first);
112 previous = tuple.second;
114 if (totalWidth - previous > dilationAmount) {
115 result.append(previous);
116 result.append(totalWidth);
122 static void drawSkipInkUnderline(TextPainter& textPainter, GraphicsContext& context, FloatPoint localOrigin, float underlineOffset, float width, bool isPrinting, bool doubleLines)
124 FloatPoint adjustedLocalOrigin = localOrigin;
125 adjustedLocalOrigin.move(0, underlineOffset);
126 FloatRect underlineBoundingBox = context.computeLineBoundsForText(adjustedLocalOrigin, width, isPrinting);
127 DashArray intersections = textPainter.dashesForIntersectionsWithRect(underlineBoundingBox);
128 DashArray a = translateIntersectionPointsToSkipInkBoundaries(intersections, underlineBoundingBox.height(), width);
130 ASSERT(!(a.size() % 2));
131 context.drawLinesForText(adjustedLocalOrigin, a, isPrinting, doubleLines);
135 InlineTextBox::~InlineTextBox()
137 if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
138 gTextBoxesWithOverflow->remove(this);
141 void InlineTextBox::markDirty(bool dirty)
147 InlineBox::markDirty(dirty);
150 LayoutRect InlineTextBox::logicalOverflowRect() const
152 if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow)
153 return enclosingIntRect(logicalFrameRect());
154 return gTextBoxesWithOverflow->get(this);
157 void InlineTextBox::setLogicalOverflowRect(const LayoutRect& rect)
159 ASSERT(!knownToHaveNoOverflow());
160 if (!gTextBoxesWithOverflow)
161 gTextBoxesWithOverflow = new InlineTextBoxOverflowMap;
162 gTextBoxesWithOverflow->add(this, rect);
165 int InlineTextBox::baselinePosition(FontBaseline baselineType) const
169 if (&parent()->renderer() == renderer().parent())
170 return parent()->baselinePosition(baselineType);
171 return toRenderBoxModelObject(renderer().parent())->baselinePosition(baselineType, isFirstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
174 LayoutUnit InlineTextBox::lineHeight() const
176 if (!renderer().parent())
178 if (&parent()->renderer() == renderer().parent())
179 return parent()->lineHeight();
180 return toRenderBoxModelObject(renderer().parent())->lineHeight(isFirstLine(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
183 LayoutUnit InlineTextBox::selectionTop() const
185 return root().selectionTop();
188 LayoutUnit InlineTextBox::selectionBottom() const
190 return root().selectionBottom();
193 LayoutUnit InlineTextBox::selectionHeight() const
195 return root().selectionHeight();
198 bool InlineTextBox::isSelected(int startPos, int endPos) const
200 int sPos = std::max(startPos - m_start, 0);
201 int ePos = std::min(endPos - m_start, static_cast<int>(m_len));
202 return (sPos < ePos);
205 RenderObject::SelectionState InlineTextBox::selectionState()
207 RenderObject::SelectionState state = renderer().selectionState();
208 if (state == RenderObject::SelectionStart || state == RenderObject::SelectionEnd || state == RenderObject::SelectionBoth) {
209 int startPos, endPos;
210 renderer().selectionStartEnd(startPos, endPos);
211 // The position after a hard line break is considered to be past its end.
212 int lastSelectable = start() + len() - (isLineBreak() ? 1 : 0);
214 bool start = (state != RenderObject::SelectionEnd && startPos >= m_start && startPos < m_start + m_len);
215 bool end = (state != RenderObject::SelectionStart && endPos > m_start && endPos <= lastSelectable);
217 state = RenderObject::SelectionBoth;
219 state = RenderObject::SelectionStart;
221 state = RenderObject::SelectionEnd;
222 else if ((state == RenderObject::SelectionEnd || startPos < m_start) &&
223 (state == RenderObject::SelectionStart || endPos > lastSelectable))
224 state = RenderObject::SelectionInside;
225 else if (state == RenderObject::SelectionBoth)
226 state = RenderObject::SelectionNone;
229 // If there are ellipsis following, make sure their selection is updated.
230 if (m_truncation != cNoTruncation && root().ellipsisBox()) {
231 EllipsisBox* ellipsis = root().ellipsisBox();
232 if (state != RenderObject::SelectionNone) {
234 selectionStartEnd(start, end);
235 // The ellipsis should be considered to be selected if the end of
236 // the selection is past the beginning of the truncation and the
237 // beginning of the selection is before or at the beginning of the
239 ellipsis->setSelectionState(end >= m_truncation && start <= m_truncation ?
240 RenderObject::SelectionInside : RenderObject::SelectionNone);
242 ellipsis->setSelectionState(RenderObject::SelectionNone);
248 static void adjustCharactersAndLengthForHyphen(BufferForAppendingHyphen& charactersWithHyphen, const RenderStyle& style, String& string, int& length)
250 const AtomicString& hyphenString = style.hyphenString();
251 charactersWithHyphen.reserveCapacity(length + hyphenString.length());
252 charactersWithHyphen.append(string);
253 charactersWithHyphen.append(hyphenString);
254 string = charactersWithHyphen.toString();
255 length += hyphenString.length();
258 static const Font& fontToUse(const RenderStyle& style, const RenderText& renderer)
260 if (style.hasTextCombine() && renderer.isCombineText()) {
261 const RenderCombineText& textCombineRenderer = toRenderCombineText(renderer);
262 if (textCombineRenderer.isCombined())
263 return textCombineRenderer.textCombineFont();
268 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos) const
270 int sPos = std::max(startPos - m_start, 0);
271 int ePos = std::min(endPos - m_start, (int)m_len);
276 FontCachePurgePreventer fontCachePurgePreventer;
278 LayoutUnit selTop = selectionTop();
279 LayoutUnit selHeight = selectionHeight();
280 const RenderStyle& lineStyle = this->lineStyle();
281 const Font& font = fontToUse(lineStyle, renderer());
283 BufferForAppendingHyphen charactersWithHyphen;
284 bool respectHyphen = ePos == m_len && hasHyphen();
285 TextRun textRun = constructTextRun(lineStyle, font, respectHyphen ? &charactersWithHyphen : 0);
287 endPos = textRun.length();
289 FloatPoint startingPoint = FloatPoint(logicalLeft(), selTop);
291 if (sPos || ePos != static_cast<int>(m_len))
292 r = enclosingIntRect(font.selectionRectForText(textRun, startingPoint, selHeight, sPos, ePos));
293 else // Avoid computing the font width when the entire line box is selected as an optimization.
294 r = enclosingIntRect(FloatRect(startingPoint, FloatSize(m_logicalWidth, selHeight)));
296 LayoutUnit logicalWidth = r.width();
297 if (r.x() > logicalRight())
299 else if (r.maxX() > logicalRight())
300 logicalWidth = logicalRight() - r.x();
302 LayoutPoint topPoint = isHorizontal() ? LayoutPoint(r.x(), selTop) : LayoutPoint(selTop, r.x());
303 LayoutUnit width = isHorizontal() ? logicalWidth : selHeight;
304 LayoutUnit height = isHorizontal() ? selHeight : logicalWidth;
306 return LayoutRect(topPoint, LayoutSize(width, height));
309 void InlineTextBox::deleteLine()
311 renderer().removeTextBox(*this);
315 void InlineTextBox::extractLine()
320 renderer().extractTextBox(*this);
323 void InlineTextBox::attachLine()
328 renderer().attachTextBox(*this);
331 float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, float visibleRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
334 m_truncation = cFullTruncation;
338 // For LTR this is the left edge of the box, for RTL, the right edge in parent coordinates.
339 float ellipsisX = flowIsLTR ? visibleRightEdge - ellipsisWidth : visibleLeftEdge + ellipsisWidth;
341 // Criteria for full truncation:
342 // LTR: the left edge of the ellipsis is to the left of our text run.
343 // RTL: the right edge of the ellipsis is to the right of our text run.
344 bool ltrFullTruncation = flowIsLTR && ellipsisX <= left();
345 bool rtlFullTruncation = !flowIsLTR && ellipsisX >= left() + logicalWidth();
346 if (ltrFullTruncation || rtlFullTruncation) {
347 // Too far. Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
348 m_truncation = cFullTruncation;
353 bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < right());
354 bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > left());
355 if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
358 // The inline box may have different directionality than it's parent. Since truncation
359 // behavior depends both on both the parent and the inline block's directionality, we
360 // must keep track of these separately.
361 bool ltr = isLeftToRightDirection();
362 if (ltr != flowIsLTR) {
363 // Width in pixels of the visible portion of the box, excluding the ellipsis.
364 int visibleBoxWidth = visibleRightEdge - visibleLeftEdge - ellipsisWidth;
365 ellipsisX = ltr ? left() + visibleBoxWidth : right() - visibleBoxWidth;
368 int offset = offsetForPosition(ellipsisX, false);
370 // No characters should be rendered. Set ourselves to full truncation and place the ellipsis at the min of our start
371 // and the ellipsis edge.
372 m_truncation = cFullTruncation;
373 truncatedWidth += ellipsisWidth;
374 return flowIsLTR ? std::min(ellipsisX, x()) : std::max(ellipsisX, right() - ellipsisWidth);
377 // Set the truncation index on the text run.
378 m_truncation = offset;
380 // If we got here that means that we were only partially truncated and we need to return the pixel offset at which
381 // to place the ellipsis.
382 float widthOfVisibleText = renderer().width(m_start, offset, textPos(), isFirstLine());
384 // The ellipsis needs to be placed just after the last visible character.
385 // Where "after" is defined by the flow directionality, not the inline
386 // box directionality.
387 // e.g. In the case of an LTR inline box truncated in an RTL flow then we can
388 // have a situation such as |Hello| -> |...He|
389 truncatedWidth += widthOfVisibleText + ellipsisWidth;
391 return left() + widthOfVisibleText;
393 return right() - widthOfVisibleText - ellipsisWidth;
395 truncatedWidth += logicalWidth();
401 bool InlineTextBox::isLineBreak() const
403 return renderer().style().preserveNewline() && len() == 1 && (*renderer().text())[start()] == '\n';
406 bool InlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
408 if (!visibleToHitTesting())
414 if (m_truncation == cFullTruncation)
417 FloatRect rect(locationIncludingFlipping(), size());
418 // Make sure truncated text is ignored while hittesting.
419 if (m_truncation != cNoTruncation) {
420 LayoutUnit widthOfVisibleText = renderer().width(m_start, m_truncation, textPos(), isFirstLine());
423 renderer().style().isLeftToRightDirection() ? rect.setWidth(widthOfVisibleText) : rect.shiftXEdgeTo(right() - widthOfVisibleText);
425 rect.setHeight(widthOfVisibleText);
428 rect.moveBy(accumulatedOffset);
430 if (locationInContainer.intersects(rect)) {
431 renderer().updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - toLayoutSize(accumulatedOffset)));
432 if (!result.addNodeToRectBasedTestResult(renderer().textNode(), request, locationInContainer, rect))
438 FloatSize InlineTextBox::applyShadowToGraphicsContext(GraphicsContext* context, const ShadowData* shadow, const FloatRect& textRect, bool stroked, bool opaque, bool horizontal)
443 FloatSize extraOffset;
444 int shadowX = horizontal ? shadow->x() : shadow->y();
445 int shadowY = horizontal ? shadow->y() : -shadow->x();
446 FloatSize shadowOffset(shadowX, shadowY);
447 int shadowRadius = shadow->radius();
448 const Color& shadowColor = shadow->color();
450 if (shadow->next() || stroked || !opaque) {
451 FloatRect shadowRect(textRect);
452 shadowRect.inflate(shadow->paintingExtent());
453 shadowRect.move(shadowOffset);
455 context->clip(shadowRect);
457 extraOffset = FloatSize(0, 2 * textRect.height() + std::max(0.0f, shadowOffset.height()) + shadowRadius);
458 shadowOffset -= extraOffset;
461 context->setShadow(shadowOffset, shadowRadius, shadowColor, context->fillColorSpace());
465 static inline bool emphasisPositionHasNeitherLeftNorRight(TextEmphasisPosition emphasisPosition)
467 return !(emphasisPosition & TextEmphasisPositionLeft) && !(emphasisPosition & TextEmphasisPositionRight);
470 bool InlineTextBox::emphasisMarkExistsAndIsAbove(const RenderStyle& style, bool& above) const
472 // This function returns true if there are text emphasis marks and they are suppressed by ruby text.
473 if (style.textEmphasisMark() == TextEmphasisMarkNone)
476 TextEmphasisPosition emphasisPosition = style.textEmphasisPosition();
477 ASSERT(!((emphasisPosition & TextEmphasisPositionOver) && (emphasisPosition & TextEmphasisPositionUnder)));
478 ASSERT(!((emphasisPosition & TextEmphasisPositionLeft) && (emphasisPosition & TextEmphasisPositionRight)));
480 if (emphasisPositionHasNeitherLeftNorRight(emphasisPosition))
481 above = emphasisPosition & TextEmphasisPositionOver;
482 else if (style.isHorizontalWritingMode())
483 above = emphasisPosition & TextEmphasisPositionOver;
485 above = emphasisPosition & TextEmphasisPositionRight;
487 if ((style.isHorizontalWritingMode() && (emphasisPosition & TextEmphasisPositionUnder))
488 || (!style.isHorizontalWritingMode() && (emphasisPosition & TextEmphasisPositionLeft)))
489 return true; // Ruby text is always over, so it cannot suppress emphasis marks under.
491 RenderBlock* containingBlock = renderer().containingBlock();
492 if (!containingBlock->isRubyBase())
493 return true; // This text is not inside a ruby base, so it does not have ruby text over it.
495 if (!containingBlock->parent()->isRubyRun())
496 return true; // Cannot get the ruby text.
498 RenderRubyText* rubyText = toRenderRubyRun(containingBlock->parent())->rubyText();
500 // The emphasis marks over are suppressed only if there is a ruby text box and it not empty.
501 return !rubyText || !rubyText->hasLines();
504 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
506 if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(renderer()) || renderer().style().visibility() != VISIBLE
507 || m_truncation == cFullTruncation || paintInfo.phase == PaintPhaseOutline || !m_len)
510 ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
512 LayoutUnit logicalLeftSide = logicalLeftVisualOverflow();
513 LayoutUnit logicalRightSide = logicalRightVisualOverflow();
514 LayoutUnit logicalStart = logicalLeftSide + (isHorizontal() ? paintOffset.x() : paintOffset.y());
515 LayoutUnit logicalExtent = logicalRightSide - logicalLeftSide;
517 LayoutUnit paintEnd = isHorizontal() ? paintInfo.rect.maxX() : paintInfo.rect.maxY();
518 LayoutUnit paintStart = isHorizontal() ? paintInfo.rect.x() : paintInfo.rect.y();
520 FloatPoint adjustedPaintOffset = roundedForPainting(paintOffset, renderer().document().deviceScaleFactor());
522 if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
525 bool isPrinting = renderer().document().printing();
527 // Determine whether or not we're selected.
528 bool haveSelection = !isPrinting && paintInfo.phase != PaintPhaseTextClip && selectionState() != RenderObject::SelectionNone;
529 if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
530 // When only painting the selection, don't bother to paint if there is none.
533 if (m_truncation != cNoTruncation) {
534 if (renderer().containingBlock()->style().isLeftToRightDirection() != isLeftToRightDirection()) {
535 // Make the visible fragment of text hug the edge closest to the rest of the run by moving the origin
536 // at which we start drawing text.
537 // e.g. In the case of LTR text truncated in an RTL Context, the correct behavior is:
538 // |Hello|CBA| -> |...He|CBA|
539 // In order to draw the fragment "He" aligned to the right edge of it's box, we need to start drawing
540 // farther to the right.
541 // NOTE: WebKit's behavior differs from that of IE which appears to just overlay the ellipsis on top of the
542 // truncated string i.e. |Hello|CBA| -> |...lo|CBA|
543 LayoutUnit widthOfVisibleText = renderer().width(m_start, m_truncation, textPos(), isFirstLine());
544 LayoutUnit widthOfHiddenText = m_logicalWidth - widthOfVisibleText;
545 LayoutSize truncationOffset(isLeftToRightDirection() ? widthOfHiddenText : -widthOfHiddenText, 0);
546 adjustedPaintOffset.move(isHorizontal() ? truncationOffset : truncationOffset.transposedSize());
550 GraphicsContext* context = paintInfo.context;
552 const RenderStyle& lineStyle = this->lineStyle();
554 adjustedPaintOffset.move(0, lineStyle.isHorizontalWritingMode() ? 0 : -logicalHeight());
556 FloatPoint boxOrigin = locationIncludingFlipping();
557 boxOrigin.move(adjustedPaintOffset.x(), adjustedPaintOffset.y());
558 FloatRect boxRect(boxOrigin, FloatSize(logicalWidth(), logicalHeight()));
560 RenderCombineText* combinedText = lineStyle.hasTextCombine() && renderer().isCombineText() && toRenderCombineText(renderer()).isCombined() ? &toRenderCombineText(renderer()) : 0;
562 bool shouldRotate = !isHorizontal() && !combinedText;
564 context->concatCTM(rotation(boxRect, Clockwise));
566 // Determine whether or not we have composition underlines to draw.
567 bool containsComposition = renderer().textNode() && renderer().frame().editor().compositionNode() == renderer().textNode();
568 bool useCustomUnderlines = containsComposition && renderer().frame().editor().compositionUsesCustomUnderlines();
570 // Determine the text colors and selection colors.
571 TextPaintStyle textPaintStyle = computeTextPaintStyle(renderer(), lineStyle, paintInfo);
573 bool paintSelectedTextOnly;
574 bool paintSelectedTextSeparately;
575 const ShadowData* selectionShadow;
576 TextPaintStyle selectionPaintStyle = computeTextSelectionPaintStyle(textPaintStyle, renderer(), lineStyle, paintInfo, paintSelectedTextOnly, paintSelectedTextSeparately, selectionShadow);
579 const Font& font = fontToUse(lineStyle, renderer());
581 FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
584 combinedText->adjustTextOrigin(textOrigin, boxRect);
586 // 1. Paint backgrounds behind text if needed. Examples of such backgrounds include selection
587 // and composition underlines.
588 if (paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseTextClip && !isPrinting) {
589 if (containsComposition && !useCustomUnderlines)
590 paintCompositionBackground(context, boxOrigin, lineStyle, font,
591 renderer().frame().editor().compositionStart(),
592 renderer().frame().editor().compositionEnd());
594 paintDocumentMarkers(context, boxOrigin, lineStyle, font, true);
596 if (haveSelection && !useCustomUnderlines)
597 paintSelection(context, boxOrigin, lineStyle, font, selectionPaintStyle.fillColor);
600 if (Page* page = renderer().frame().page()) {
601 // FIXME: Right now, InlineTextBoxes never call addRelevantUnpaintedObject() even though they might
602 // legitimately be unpainted if they are waiting on a slow-loading web font. We should fix that, and
603 // when we do, we will have to account for the fact the InlineTextBoxes do not always have unique
604 // renderers and Page currently relies on each unpainted object having a unique renderer.
605 if (paintInfo.phase == PaintPhaseForeground)
606 page->addRelevantRepaintedObject(&renderer(), IntRect(boxOrigin.x(), boxOrigin.y(), logicalWidth(), logicalHeight()));
609 // 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
614 string = renderer().text();
615 if (static_cast<unsigned>(length) != string.length() || m_start) {
616 ASSERT_WITH_SECURITY_IMPLICATION(static_cast<unsigned>(m_start + length) <= string.length());
617 string = string.substringSharingImpl(m_start, length);
619 maximumLength = renderer().textLength() - m_start;
621 combinedText->getStringToRender(m_start, string, length);
622 maximumLength = length;
625 BufferForAppendingHyphen charactersWithHyphen;
626 TextRun textRun = constructTextRun(lineStyle, font, string, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
628 length = textRun.length();
632 if (haveSelection && (paintSelectedTextOnly || paintSelectedTextSeparately))
633 selectionStartEnd(sPos, ePos);
635 if (m_truncation != cNoTruncation) {
636 sPos = std::min<int>(sPos, m_truncation);
637 ePos = std::min<int>(ePos, m_truncation);
638 length = m_truncation;
641 int emphasisMarkOffset = 0;
642 bool emphasisMarkAbove;
643 bool hasTextEmphasis = emphasisMarkExistsAndIsAbove(lineStyle, emphasisMarkAbove);
644 const AtomicString& emphasisMark = hasTextEmphasis ? lineStyle.textEmphasisMarkString() : nullAtom;
645 if (!emphasisMark.isEmpty())
646 emphasisMarkOffset = emphasisMarkAbove ? -font.fontMetrics().ascent() - font.emphasisMarkDescent(emphasisMark) : font.fontMetrics().descent() + font.emphasisMarkAscent(emphasisMark);
648 const ShadowData* textShadow = paintInfo.forceBlackText() ? 0 : lineStyle.textShadow();
650 TextPainter textPainter(*context, paintSelectedTextOnly, paintSelectedTextSeparately, font, sPos, ePos, length, emphasisMark, combinedText, textRun, boxRect, textOrigin, emphasisMarkOffset, textShadow, selectionShadow, isHorizontal(), textPaintStyle, selectionPaintStyle);
651 textPainter.paintText();
654 TextDecoration textDecorations = lineStyle.textDecorationsInEffect();
655 if (textDecorations != TextDecorationNone && paintInfo.phase != PaintPhaseSelection) {
656 updateGraphicsContext(*context, textPaintStyle);
658 context->concatCTM(rotation(boxRect, Clockwise));
659 paintDecoration(*context, boxOrigin, textDecorations, lineStyle.textDecorationStyle(), textShadow, textPainter);
661 context->concatCTM(rotation(boxRect, Counterclockwise));
664 if (paintInfo.phase == PaintPhaseForeground) {
665 paintDocumentMarkers(context, boxOrigin, lineStyle, font, false);
667 if (useCustomUnderlines) {
668 const Vector<CompositionUnderline>& underlines = renderer().frame().editor().customCompositionUnderlines();
669 size_t numUnderlines = underlines.size();
671 for (size_t index = 0; index < numUnderlines; ++index) {
672 const CompositionUnderline& underline = underlines[index];
674 if (underline.endOffset <= start())
675 // underline is completely before this run. This might be an underline that sits
676 // before the first run we draw, or underlines that were within runs we skipped
677 // due to truncation.
680 if (underline.startOffset <= end()) {
681 // underline intersects this run. Paint it.
682 paintCompositionUnderline(context, boxOrigin, underline);
683 if (underline.endOffset > end() + 1)
684 // underline also runs into the next run. Bail now, no more marker advancement.
687 // underline is completely after this run, bail. A later run will paint it.
694 context->concatCTM(rotation(boxRect, Counterclockwise));
697 void InlineTextBox::selectionStartEnd(int& sPos, int& ePos)
699 int startPos, endPos;
700 if (renderer().selectionState() == RenderObject::SelectionInside) {
702 endPos = renderer().textLength();
704 renderer().selectionStartEnd(startPos, endPos);
705 if (renderer().selectionState() == RenderObject::SelectionStart)
706 endPos = renderer().textLength();
707 else if (renderer().selectionState() == RenderObject::SelectionEnd)
711 sPos = std::max(startPos - m_start, 0);
712 ePos = std::min(endPos - m_start, (int)m_len);
715 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, Color textColor)
717 #if ENABLE(TEXT_SELECTION)
718 if (context->paintingDisabled())
721 // See if we have a selection to paint at all.
723 selectionStartEnd(sPos, ePos);
727 Color c = renderer().selectionBackgroundColor();
728 if (!c.isValid() || c.alpha() == 0)
731 // If the text color ends up being the same as the selection background, invert the selection
734 c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
736 GraphicsContextStateSaver stateSaver(*context);
737 updateGraphicsContext(*context, TextPaintStyle(c, style.colorSpace())); // Don't draw text at all!
739 // If the text is truncated, let the thing being painted in the truncation
740 // draw its own highlight.
741 int length = m_truncation != cNoTruncation ? m_truncation : m_len;
742 String string = renderer().text();
744 if (string.length() != static_cast<unsigned>(length) || m_start) {
745 ASSERT_WITH_SECURITY_IMPLICATION(static_cast<unsigned>(m_start + length) <= string.length());
746 string = string.substringSharingImpl(m_start, length);
749 BufferForAppendingHyphen charactersWithHyphen;
750 bool respectHyphen = ePos == length && hasHyphen();
751 TextRun textRun = constructTextRun(style, font, string, renderer().textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
753 ePos = textRun.length();
755 const RootInlineBox& rootBox = root();
756 LayoutUnit selectionBottom = rootBox.selectionBottom();
757 LayoutUnit selectionTop = rootBox.selectionTopAdjustedForPrecedingBlock();
759 LayoutUnit deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop;
760 LayoutUnit selectionHeight = std::max<LayoutUnit>(0, selectionBottom - selectionTop);
762 float deviceScaleFactor = renderer().document().deviceScaleFactor();
763 FloatPoint localOrigin = roundedForPainting(LayoutPoint(boxOrigin.x(), boxOrigin.y() - deltaY), deviceScaleFactor);
764 context->clip(pixelSnappedForPainting(LayoutRect(LayoutPoint(localOrigin), LayoutSize(m_logicalWidth, selectionHeight)), deviceScaleFactor));
765 context->drawHighlightForText(font, textRun, localOrigin, selectionHeight, c, style.colorSpace(), sPos, ePos);
767 UNUSED_PARAM(context);
768 UNUSED_PARAM(boxOrigin);
771 UNUSED_PARAM(textColor);
775 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, int startPos, int endPos)
777 int offset = m_start;
778 int sPos = std::max(startPos - offset, 0);
779 int ePos = std::min(endPos - offset, (int)m_len);
784 GraphicsContextStateSaver stateSaver(*context);
787 // FIXME: Is this color still applicable as of Mavericks? for non-Mac ports? We should
788 // be able to move this color information to RenderStyle.
789 Color c = Color(225, 221, 85);
791 Color c = style.compositionFillColor();
794 updateGraphicsContext(*context, TextPaintStyle(c, style.colorSpace())); // Don't draw text at all!
796 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
797 int selHeight = selectionHeight();
798 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
799 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style.colorSpace(), sPos, ePos);
802 static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorationStyle)
804 StrokeStyle strokeStyle = SolidStroke;
805 switch (decorationStyle) {
806 case TextDecorationStyleSolid:
807 strokeStyle = SolidStroke;
809 case TextDecorationStyleDouble:
810 strokeStyle = DoubleStroke;
812 case TextDecorationStyleDotted:
813 strokeStyle = DottedStroke;
815 case TextDecorationStyleDashed:
816 strokeStyle = DashedStroke;
818 case TextDecorationStyleWavy:
819 strokeStyle = WavyStroke;
826 static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const int textDecorationThickness)
828 // Compute the gap between the font and the underline. Use at least one
829 // pixel gap, if underline is thick then use a bigger gap.
830 const int gap = std::max<int>(1, ceilf(textDecorationThickness / 2.0));
832 // According to the specification TextUnderlinePositionAuto should default to 'alphabetic' for horizontal text
833 // and to 'under Left' for vertical text (e.g. japanese). We support only horizontal text for now.
834 switch (underlinePosition) {
835 case TextUnderlinePositionAlphabetic:
836 case TextUnderlinePositionAuto:
837 return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
838 case TextUnderlinePositionUnder: {
839 // Position underline relative to the under edge of the lowest element's content box.
840 const float offset = inlineTextBox->root().maxLogicalTop() - inlineTextBox->logicalTop();
841 return inlineTextBox->logicalHeight() + gap + std::max<float>(offset, 0);
845 ASSERT_NOT_REACHED();
846 return fontMetrics.ascent() + gap;
849 static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
856 unsigned stepCount = static_cast<unsigned>(length / step);
858 // Each Bezier curve starts at the same pixel that the previous one
859 // ended. We need to subtract (stepCount - 1) pixels when calculating the
860 // length covered to account for that.
861 float uncoveredLength = length - (stepCount * step - (stepCount - 1));
862 float adjustment = uncoveredLength / stepCount;
864 controlPointDistance += adjustment;
867 static void getWavyStrokeParameters(float strokeThickness, float& controlPointDistance, float& step)
869 // Distance between decoration's axis and Bezier curve's control points.
870 // The height of the curve is based on this distance. Use a minimum of 6 pixels distance since
871 // the actual curve passes approximately at half of that distance, that is 3 pixels.
872 // The minimum height of the curve is also approximately 3 pixels. Increases the curve's height
873 // as strockThickness increases to make the curve looks better.
874 controlPointDistance = 3 * std::max<float>(2, strokeThickness);
876 // Increment used to form the diamond shape between start point (p1), control
877 // points and end point (p2) along the axis of the decoration. Makes the
878 // curve wider as strockThickness increases to make the curve looks better.
879 step = 2 * std::max<float>(2, strokeThickness);
883 * Draw one cubic Bezier curve and repeat the same pattern long the the decoration's axis.
884 * The start point (p1), controlPoint1, controlPoint2 and end point (p2) of the Bezier curve
885 * form a diamond shape:
897 * (x1, y1) p1 + . + p2 (x2, y2) - <--- Decoration's axis
900 * . . | controlPointDistance
909 static void strokeWavyTextDecoration(GraphicsContext& context, FloatPoint& p1, FloatPoint& p2, float strokeThickness)
911 context.adjustLineToPixelBoundaries(p1, p2, strokeThickness, context.strokeStyle());
916 float controlPointDistance;
918 getWavyStrokeParameters(strokeThickness, controlPointDistance, step);
920 bool isVerticalLine = (p1.x() == p2.x());
922 if (isVerticalLine) {
923 ASSERT(p1.x() == p2.x());
925 float xAxis = p1.x();
929 if (p1.y() < p2.y()) {
937 adjustStepToDecorationLength(step, controlPointDistance, y2 - y1);
938 FloatPoint controlPoint1(xAxis + controlPointDistance, 0);
939 FloatPoint controlPoint2(xAxis - controlPointDistance, 0);
941 for (float y = y1; y + 2 * step <= y2;) {
942 controlPoint1.setY(y + step);
943 controlPoint2.setY(y + step);
945 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(xAxis, y));
948 ASSERT(p1.y() == p2.y());
950 float yAxis = p1.y();
954 if (p1.x() < p2.x()) {
962 adjustStepToDecorationLength(step, controlPointDistance, x2 - x1);
963 FloatPoint controlPoint1(0, yAxis + controlPointDistance);
964 FloatPoint controlPoint2(0, yAxis - controlPointDistance);
966 for (float x = x1; x + 2 * step <= x2;) {
967 controlPoint1.setX(x + step);
968 controlPoint2.setX(x + step);
970 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(x, yAxis));
974 context.setShouldAntialias(true);
975 context.strokePath(path);
978 void InlineTextBox::paintDecoration(GraphicsContext& context, const FloatPoint& boxOrigin, TextDecoration decoration, TextDecorationStyle decorationStyle, const ShadowData* shadow, TextPainter& textPainter)
980 #if !ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
981 UNUSED_PARAM(textPainter);
984 // FIXME: We should improve this rule and not always just assume 1.
985 const float textDecorationThickness = 1.f;
987 if (m_truncation == cFullTruncation)
990 FloatPoint localOrigin = boxOrigin;
992 float width = m_logicalWidth;
993 if (m_truncation != cNoTruncation) {
994 width = renderer().width(m_start, m_truncation, textPos(), isFirstLine());
995 if (!isLeftToRightDirection())
996 localOrigin.move(m_logicalWidth - width, 0);
999 // Get the text decoration colors.
1000 Color underline, overline, linethrough;
1001 renderer().getTextDecorationColors(decoration, underline, overline, linethrough, true);
1003 renderer().getTextDecorationColors(decoration, underline, overline, linethrough, true, true);
1005 // Use a special function for underlines to get the positioning exactly right.
1006 bool isPrinting = renderer().document().printing();
1008 const float textDecorationBaseFontSize = 16;
1009 float fontSizeScaling = renderer().style().fontSize() / textDecorationBaseFontSize;
1010 float strokeThickness = roundf(textDecorationThickness * fontSizeScaling);
1011 context.setStrokeThickness(strokeThickness);
1013 bool linesAreOpaque = !isPrinting && (!(decoration & TextDecorationUnderline) || underline.alpha() == 255) && (!(decoration & TextDecorationOverline) || overline.alpha() == 255) && (!(decoration & TextDecorationLineThrough) || linethrough.alpha() == 255);
1015 const RenderStyle& lineStyle = this->lineStyle();
1016 int baseline = lineStyle.fontMetrics().ascent();
1018 bool setClip = false;
1019 int extraOffset = 0;
1020 if (!linesAreOpaque && shadow && shadow->next()) {
1021 FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1022 for (const ShadowData* s = shadow; s; s = s->next()) {
1023 int shadowExtent = s->paintingExtent();
1024 FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1025 shadowRect.inflate(shadowExtent);
1026 int shadowX = isHorizontal() ? s->x() : s->y();
1027 int shadowY = isHorizontal() ? s->y() : -s->x();
1028 shadowRect.move(shadowX, shadowY);
1029 clipRect.unite(shadowRect);
1030 extraOffset = std::max(extraOffset, std::max(0, shadowY) + shadowExtent);
1033 context.clip(clipRect);
1034 extraOffset += baseline + 2;
1035 localOrigin.move(0, extraOffset);
1039 ColorSpace colorSpace = renderer().style().colorSpace();
1040 bool setShadow = false;
1044 if (!shadow->next()) {
1045 // The last set of lines paints normally inside the clip.
1046 localOrigin.move(0, -extraOffset);
1049 int shadowX = isHorizontal() ? shadow->x() : shadow->y();
1050 int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
1051 context.setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->radius(), shadow->color(), colorSpace);
1053 shadow = shadow->next();
1056 float wavyOffset = 2.f;
1058 context.setStrokeStyle(textDecorationStyleToStrokeStyle(decorationStyle));
1059 if (decoration & TextDecorationUnderline) {
1060 context.setStrokeColor(underline, colorSpace);
1061 TextUnderlinePosition underlinePosition = lineStyle.textUnderlinePosition();
1062 const int underlineOffset = computeUnderlineOffset(underlinePosition, lineStyle.fontMetrics(), this, textDecorationThickness);
1064 switch (decorationStyle) {
1065 case TextDecorationStyleWavy: {
1066 FloatPoint start(localOrigin.x(), localOrigin.y() + underlineOffset + wavyOffset);
1067 FloatPoint end(localOrigin.x() + width, localOrigin.y() + underlineOffset + wavyOffset);
1068 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1072 #if ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
1073 if ((lineStyle.textDecorationSkip() == TextDecorationSkipInk || lineStyle.textDecorationSkip() == TextDecorationSkipAuto) && isHorizontal()) {
1074 if (!context.paintingDisabled()) {
1075 drawSkipInkUnderline(textPainter, context, localOrigin, underlineOffset, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1078 // FIXME: Need to support text-decoration-skip: none.
1079 #endif // CSS3_TEXT_DECORATION_SKIP_INK
1080 context.drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + underlineOffset), width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1083 if (decoration & TextDecorationOverline) {
1084 context.setStrokeColor(overline, colorSpace);
1085 switch (decorationStyle) {
1086 case TextDecorationStyleWavy: {
1087 FloatPoint start(localOrigin.x(), localOrigin.y() - wavyOffset);
1088 FloatPoint end(localOrigin.x() + width, localOrigin.y() - wavyOffset);
1089 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1093 #if ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
1094 if ((lineStyle.textDecorationSkip() == TextDecorationSkipInk || lineStyle.textDecorationSkip() == TextDecorationSkipAuto) && isHorizontal()) {
1095 if (!context.paintingDisabled())
1096 drawSkipInkUnderline(textPainter, context, localOrigin, 0, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1098 // FIXME: Need to support text-decoration-skip: none.
1099 #endif // CSS3_TEXT_DECORATION_SKIP_INK
1100 context.drawLineForText(localOrigin, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1103 if (decoration & TextDecorationLineThrough) {
1104 context.setStrokeColor(linethrough, colorSpace);
1105 switch (decorationStyle) {
1106 case TextDecorationStyleWavy: {
1107 FloatPoint start(localOrigin.x(), localOrigin.y() + 2 * baseline / 3);
1108 FloatPoint end(localOrigin.x() + width, localOrigin.y() + 2 * baseline / 3);
1109 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1113 context.drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1121 context.clearShadow();
1124 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1126 switch (markerType) {
1127 case DocumentMarker::Spelling:
1128 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1129 case DocumentMarker::Grammar:
1130 return GraphicsContext::DocumentMarkerGrammarLineStyle;
1131 case DocumentMarker::CorrectionIndicator:
1132 return GraphicsContext::DocumentMarkerAutocorrectionReplacementLineStyle;
1133 case DocumentMarker::DictationAlternatives:
1134 return GraphicsContext::DocumentMarkerDictationAlternativesLineStyle;
1136 case DocumentMarker::DictationPhraseWithAlternatives:
1137 // FIXME: Rename TextCheckingDictationPhraseWithAlternativesLineStyle and remove the PLATFORM(IOS)-guard.
1138 return GraphicsContext::TextCheckingDictationPhraseWithAlternativesLineStyle;
1141 ASSERT_NOT_REACHED();
1142 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1146 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, const RenderStyle& style, const Font& font, bool grammar)
1148 // Never print spelling/grammar markers (5327887)
1149 if (renderer().document().printing())
1152 if (m_truncation == cFullTruncation)
1155 float start = 0; // start of line to draw, relative to tx
1156 float width = m_logicalWidth; // how much line to draw
1158 // Determine whether we need to measure text
1159 bool markerSpansWholeBox = true;
1160 if (m_start <= (int)marker->startOffset())
1161 markerSpansWholeBox = false;
1162 if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1163 markerSpansWholeBox = false;
1164 if (m_truncation != cNoTruncation)
1165 markerSpansWholeBox = false;
1167 bool isDictationMarker = marker->type() == DocumentMarker::DictationAlternatives;
1168 if (!markerSpansWholeBox || grammar || isDictationMarker) {
1169 int startPosition = std::max<int>(marker->startOffset() - m_start, 0);
1170 int endPosition = std::min<int>(marker->endOffset() - m_start, m_len);
1172 if (m_truncation != cNoTruncation)
1173 endPosition = std::min<int>(endPosition, m_truncation);
1175 // Calculate start & width
1176 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1177 int selHeight = selectionHeight();
1178 FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1179 TextRun run = constructTextRun(style, font);
1181 // FIXME: Convert the document markers to float rects.
1182 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1183 start = markerRect.x() - startPoint.x();
1184 width = markerRect.width();
1186 // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1187 // display a toolTip. We don't do this for misspelling markers.
1188 if (grammar || isDictationMarker) {
1189 markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1190 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1191 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1195 // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1196 // make sure to fit within those bounds. This means the top pixel(s) of the underline will overlap the
1197 // bottom pixel(s) of the glyphs in smaller font sizes. The alternatives are to increase the line spacing (bad!!)
1198 // or decrease the underline thickness. The overlap is actually the most useful, and matches what AppKit does.
1199 // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1200 // we pin to two pixels under the baseline.
1201 int lineThickness = cMisspellingLineThickness;
1202 int baseline = lineStyle().fontMetrics().ascent();
1203 int descent = logicalHeight() - baseline;
1204 int underlineOffset;
1205 if (descent <= (2 + lineThickness)) {
1206 // Place the underline at the very bottom of the text in small/medium fonts.
1207 underlineOffset = logicalHeight() - lineThickness;
1209 // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1210 underlineOffset = baseline + 2;
1212 pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1215 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, const RenderStyle& style, const Font& font)
1217 // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1218 // the same word there are no pieces sticking out.
1219 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1220 int selHeight = selectionHeight();
1222 int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1223 int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1224 TextRun run = constructTextRun(style, font);
1226 // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1227 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1228 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1229 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1231 // Optionally highlight the text
1232 if (renderer().frame().editor().markedTextMatchesAreHighlighted()) {
1233 Color color = marker->activeMatch() ? renderer().theme().platformActiveTextSearchHighlightColor() : renderer().theme().platformInactiveTextSearchHighlightColor();
1234 GraphicsContextStateSaver stateSaver(*pt);
1235 updateGraphicsContext(*pt, TextPaintStyle(color, style.colorSpace())); // Don't draw text at all!
1236 pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1237 pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style.colorSpace(), sPos, ePos);
1241 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, const RenderStyle& style, const Font& font)
1243 // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
1244 int top = selectionTop();
1245 int h = selectionHeight();
1247 int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1248 int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1249 TextRun run = constructTextRun(style, font);
1250 IntPoint startPoint = IntPoint(x(), top);
1252 // Compute and store the rect associated with this marker.
1253 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, h, sPos, ePos));
1254 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1255 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1258 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, bool background)
1260 if (!renderer().textNode())
1263 Vector<DocumentMarker*> markers = renderer().document().markers().markersFor(renderer().textNode());
1264 Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1266 // Give any document markers that touch this run a chance to draw before the text has been drawn.
1267 // Note end() points at the last char, not one past it like endOffset and ranges do.
1268 for ( ; markerIt != markers.end(); ++markerIt) {
1269 DocumentMarker* marker = *markerIt;
1271 // Paint either the background markers or the foreground markers, but not both
1272 switch (marker->type()) {
1273 case DocumentMarker::Grammar:
1274 case DocumentMarker::Spelling:
1275 case DocumentMarker::CorrectionIndicator:
1276 case DocumentMarker::Replacement:
1277 case DocumentMarker::DictationAlternatives:
1279 // FIXME: Remove the PLATFORM(IOS)-guard.
1280 case DocumentMarker::DictationPhraseWithAlternatives:
1285 case DocumentMarker::TextMatch:
1286 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1287 case DocumentMarker::TelephoneNumber:
1296 if (marker->endOffset() <= start())
1297 // marker is completely before this run. This might be a marker that sits before the
1298 // first run we draw, or markers that were within runs we skipped due to truncation.
1301 if (marker->startOffset() > end())
1302 // marker is completely after this run, bail. A later run will paint it.
1305 // marker intersects this run. Paint it.
1306 switch (marker->type()) {
1307 case DocumentMarker::Spelling:
1308 case DocumentMarker::CorrectionIndicator:
1309 case DocumentMarker::DictationAlternatives:
1310 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1312 case DocumentMarker::Grammar:
1313 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1316 // FIXME: See <rdar://problem/8933352>. Also, remove the PLATFORM(IOS)-guard.
1317 case DocumentMarker::DictationPhraseWithAlternatives:
1318 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1321 case DocumentMarker::TextMatch:
1322 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1324 case DocumentMarker::Replacement:
1325 computeRectForReplacementMarker(marker, style, font);
1327 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1328 case DocumentMarker::TelephoneNumber:
1332 ASSERT_NOT_REACHED();
1338 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1340 if (m_truncation == cFullTruncation)
1343 float start = 0; // start of line to draw, relative to tx
1344 float width = m_logicalWidth; // how much line to draw
1345 bool useWholeWidth = true;
1346 unsigned paintStart = m_start;
1347 unsigned paintEnd = end() + 1; // end points at the last char, not past it
1348 if (paintStart <= underline.startOffset) {
1349 paintStart = underline.startOffset;
1350 useWholeWidth = false;
1351 start = renderer().width(m_start, paintStart - m_start, textPos(), isFirstLine());
1353 if (paintEnd != underline.endOffset) { // end points at the last char, not past it
1354 paintEnd = std::min(paintEnd, (unsigned)underline.endOffset);
1355 useWholeWidth = false;
1357 if (m_truncation != cNoTruncation) {
1358 paintEnd = std::min(paintEnd, (unsigned)m_start + m_truncation);
1359 useWholeWidth = false;
1361 if (!useWholeWidth) {
1362 width = renderer().width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLine());
1365 // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1366 // All other marked text underlines are 1px thick.
1367 // If there's not enough space the underline will touch or overlap characters.
1368 int lineThickness = 1;
1369 int baseline = lineStyle().fontMetrics().ascent();
1370 if (underline.thick && logicalHeight() - baseline >= 2)
1373 // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1374 // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1378 ctx->setStrokeColor(underline.color, renderer().style().colorSpace());
1379 ctx->setStrokeThickness(lineThickness);
1380 ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, renderer().document().printing());
1383 int InlineTextBox::caretMinOffset() const
1388 int InlineTextBox::caretMaxOffset() const
1390 return m_start + m_len;
1393 float InlineTextBox::textPos() const
1395 // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1396 // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1397 if (logicalLeft() == 0)
1399 return logicalLeft() - root().logicalLeft();
1402 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1407 if (lineOffset - logicalLeft() > logicalWidth())
1408 return isLeftToRightDirection() ? len() : 0;
1409 if (lineOffset - logicalLeft() < 0)
1410 return isLeftToRightDirection() ? 0 : len();
1412 FontCachePurgePreventer fontCachePurgePreventer;
1414 const RenderStyle& lineStyle = this->lineStyle();
1415 const Font& font = fontToUse(lineStyle, renderer());
1416 return font.offsetForPosition(constructTextRun(lineStyle, font), lineOffset - logicalLeft(), includePartialGlyphs);
1419 float InlineTextBox::positionForOffset(int offset) const
1421 ASSERT(offset >= m_start);
1422 ASSERT(offset <= m_start + m_len);
1425 return logicalLeft();
1427 FontCachePurgePreventer fontCachePurgePreventer;
1429 const RenderStyle& lineStyle = this->lineStyle();
1430 const Font& font = fontToUse(lineStyle, renderer());
1431 int from = !isLeftToRightDirection() ? offset - m_start : 0;
1432 int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1433 // FIXME: Do we need to add rightBearing here?
1434 return font.selectionRectForText(constructTextRun(lineStyle, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1437 TextRun InlineTextBox::constructTextRun(const RenderStyle& style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1439 ASSERT(renderer().text());
1441 String string = renderer().text();
1442 unsigned startPos = start();
1443 unsigned length = len();
1445 if (string.length() != length || startPos)
1446 string = string.substringSharingImpl(startPos, length);
1448 return constructTextRun(style, font, string, renderer().textLength() - startPos, charactersWithHyphen);
1451 TextRun InlineTextBox::constructTextRun(const RenderStyle& style, const Font& font, String string, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1453 int length = string.length();
1455 if (charactersWithHyphen) {
1456 adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, string, length);
1457 maximumLength = length;
1460 ASSERT(maximumLength >= length);
1462 TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style.rtlOrdering() == VisualOrder, !renderer().canUseSimpleFontCodePath());
1463 run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
1464 if (font.isSVGFont())
1465 run.setRenderingContext(SVGTextRunRenderingContext::create(renderer()));
1467 // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1468 run.setCharactersLength(maximumLength);
1469 ASSERT(run.charactersLength() >= run.length());
1475 const char* InlineTextBox::boxName() const
1477 return "InlineTextBox";
1480 void InlineTextBox::showBox(int printedCharacters) const
1482 String value = renderer().text();
1483 value = value.substring(start(), len());
1484 value.replaceWithLiteral('\\', "\\\\");
1485 value.replaceWithLiteral('\n', "\\n");
1486 printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1487 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1489 printedCharacters = fprintf(stderr, "\t%s %p", renderer().renderName(), &renderer());
1490 const int rendererCharacterOffset = 24;
1491 for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1493 fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1498 } // namespace WebCore