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 alignSelectionRectToDevicePixels(FloatRect& rect)
717 float maxX = floorf(rect.maxX());
718 rect.setX(floorf(rect.x()));
719 rect.setWidth(roundf(maxX - rect.x()));
722 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, Color textColor)
724 #if ENABLE(TEXT_SELECTION)
725 if (context->paintingDisabled())
728 // See if we have a selection to paint at all.
730 selectionStartEnd(sPos, ePos);
734 Color c = renderer().selectionBackgroundColor();
735 if (!c.isValid() || c.alpha() == 0)
738 // If the text color ends up being the same as the selection background, invert the selection
741 c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
743 GraphicsContextStateSaver stateSaver(*context);
744 updateGraphicsContext(*context, TextPaintStyle(c, style.colorSpace())); // Don't draw text at all!
746 // If the text is truncated, let the thing being painted in the truncation
747 // draw its own highlight.
748 int length = m_truncation != cNoTruncation ? m_truncation : m_len;
749 String string = renderer().text();
751 if (string.length() != static_cast<unsigned>(length) || m_start) {
752 ASSERT_WITH_SECURITY_IMPLICATION(static_cast<unsigned>(m_start + length) <= string.length());
753 string = string.substringSharingImpl(m_start, length);
756 BufferForAppendingHyphen charactersWithHyphen;
757 bool respectHyphen = ePos == length && hasHyphen();
758 TextRun textRun = constructTextRun(style, font, string, renderer().textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
760 ePos = textRun.length();
762 const RootInlineBox& rootBox = root();
763 LayoutUnit selectionBottom = rootBox.selectionBottom();
764 LayoutUnit selectionTop = rootBox.selectionTopAdjustedForPrecedingBlock();
766 int deltaY = roundToInt(renderer().style().isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
767 int selHeight = std::max(0, roundToInt(selectionBottom - selectionTop));
769 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
770 FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
771 alignSelectionRectToDevicePixels(clipRect);
773 context->clip(clipRect);
775 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style.colorSpace(), sPos, ePos);
777 UNUSED_PARAM(context);
778 UNUSED_PARAM(boxOrigin);
781 UNUSED_PARAM(textColor);
785 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, int startPos, int endPos)
787 int offset = m_start;
788 int sPos = std::max(startPos - offset, 0);
789 int ePos = std::min(endPos - offset, (int)m_len);
794 GraphicsContextStateSaver stateSaver(*context);
797 // FIXME: Is this color still applicable as of Mavericks? for non-Mac ports? We should
798 // be able to move this color information to RenderStyle.
799 Color c = Color(225, 221, 85);
801 Color c = style.compositionFillColor();
804 updateGraphicsContext(*context, TextPaintStyle(c, style.colorSpace())); // Don't draw text at all!
806 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
807 int selHeight = selectionHeight();
808 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
809 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style.colorSpace(), sPos, ePos);
812 static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorationStyle)
814 StrokeStyle strokeStyle = SolidStroke;
815 switch (decorationStyle) {
816 case TextDecorationStyleSolid:
817 strokeStyle = SolidStroke;
819 case TextDecorationStyleDouble:
820 strokeStyle = DoubleStroke;
822 case TextDecorationStyleDotted:
823 strokeStyle = DottedStroke;
825 case TextDecorationStyleDashed:
826 strokeStyle = DashedStroke;
828 case TextDecorationStyleWavy:
829 strokeStyle = WavyStroke;
836 static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const int textDecorationThickness)
838 // Compute the gap between the font and the underline. Use at least one
839 // pixel gap, if underline is thick then use a bigger gap.
840 const int gap = std::max<int>(1, ceilf(textDecorationThickness / 2.0));
842 // According to the specification TextUnderlinePositionAuto should default to 'alphabetic' for horizontal text
843 // and to 'under Left' for vertical text (e.g. japanese). We support only horizontal text for now.
844 switch (underlinePosition) {
845 case TextUnderlinePositionAlphabetic:
846 case TextUnderlinePositionAuto:
847 return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
848 case TextUnderlinePositionUnder: {
849 // Position underline relative to the under edge of the lowest element's content box.
850 const float offset = inlineTextBox->root().maxLogicalTop() - inlineTextBox->logicalTop();
851 return inlineTextBox->logicalHeight() + gap + std::max<float>(offset, 0);
855 ASSERT_NOT_REACHED();
856 return fontMetrics.ascent() + gap;
859 static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
866 unsigned stepCount = static_cast<unsigned>(length / step);
868 // Each Bezier curve starts at the same pixel that the previous one
869 // ended. We need to subtract (stepCount - 1) pixels when calculating the
870 // length covered to account for that.
871 float uncoveredLength = length - (stepCount * step - (stepCount - 1));
872 float adjustment = uncoveredLength / stepCount;
874 controlPointDistance += adjustment;
877 static void getWavyStrokeParameters(float strokeThickness, float& controlPointDistance, float& step)
879 // Distance between decoration's axis and Bezier curve's control points.
880 // The height of the curve is based on this distance. Use a minimum of 6 pixels distance since
881 // the actual curve passes approximately at half of that distance, that is 3 pixels.
882 // The minimum height of the curve is also approximately 3 pixels. Increases the curve's height
883 // as strockThickness increases to make the curve looks better.
884 controlPointDistance = 3 * std::max<float>(2, strokeThickness);
886 // Increment used to form the diamond shape between start point (p1), control
887 // points and end point (p2) along the axis of the decoration. Makes the
888 // curve wider as strockThickness increases to make the curve looks better.
889 step = 2 * std::max<float>(2, strokeThickness);
893 * Draw one cubic Bezier curve and repeat the same pattern long the the decoration's axis.
894 * The start point (p1), controlPoint1, controlPoint2 and end point (p2) of the Bezier curve
895 * form a diamond shape:
907 * (x1, y1) p1 + . + p2 (x2, y2) - <--- Decoration's axis
910 * . . | controlPointDistance
919 static void strokeWavyTextDecoration(GraphicsContext& context, FloatPoint& p1, FloatPoint& p2, float strokeThickness)
921 context.adjustLineToPixelBoundaries(p1, p2, strokeThickness, context.strokeStyle());
926 float controlPointDistance;
928 getWavyStrokeParameters(strokeThickness, controlPointDistance, step);
930 bool isVerticalLine = (p1.x() == p2.x());
932 if (isVerticalLine) {
933 ASSERT(p1.x() == p2.x());
935 float xAxis = p1.x();
939 if (p1.y() < p2.y()) {
947 adjustStepToDecorationLength(step, controlPointDistance, y2 - y1);
948 FloatPoint controlPoint1(xAxis + controlPointDistance, 0);
949 FloatPoint controlPoint2(xAxis - controlPointDistance, 0);
951 for (float y = y1; y + 2 * step <= y2;) {
952 controlPoint1.setY(y + step);
953 controlPoint2.setY(y + step);
955 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(xAxis, y));
958 ASSERT(p1.y() == p2.y());
960 float yAxis = p1.y();
964 if (p1.x() < p2.x()) {
972 adjustStepToDecorationLength(step, controlPointDistance, x2 - x1);
973 FloatPoint controlPoint1(0, yAxis + controlPointDistance);
974 FloatPoint controlPoint2(0, yAxis - controlPointDistance);
976 for (float x = x1; x + 2 * step <= x2;) {
977 controlPoint1.setX(x + step);
978 controlPoint2.setX(x + step);
980 path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(x, yAxis));
984 context.setShouldAntialias(true);
985 context.strokePath(path);
988 void InlineTextBox::paintDecoration(GraphicsContext& context, const FloatPoint& boxOrigin, TextDecoration decoration, TextDecorationStyle decorationStyle, const ShadowData* shadow, TextPainter& textPainter)
990 #if !ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
991 UNUSED_PARAM(textPainter);
994 // FIXME: We should improve this rule and not always just assume 1.
995 const float textDecorationThickness = 1.f;
997 if (m_truncation == cFullTruncation)
1000 FloatPoint localOrigin = boxOrigin;
1002 float width = m_logicalWidth;
1003 if (m_truncation != cNoTruncation) {
1004 width = renderer().width(m_start, m_truncation, textPos(), isFirstLine());
1005 if (!isLeftToRightDirection())
1006 localOrigin.move(m_logicalWidth - width, 0);
1009 // Get the text decoration colors.
1010 Color underline, overline, linethrough;
1011 renderer().getTextDecorationColors(decoration, underline, overline, linethrough, true);
1013 renderer().getTextDecorationColors(decoration, underline, overline, linethrough, true, true);
1015 // Use a special function for underlines to get the positioning exactly right.
1016 bool isPrinting = renderer().document().printing();
1018 const float textDecorationBaseFontSize = 16;
1019 float fontSizeScaling = renderer().style().fontSize() / textDecorationBaseFontSize;
1020 float strokeThickness = roundf(textDecorationThickness * fontSizeScaling);
1021 context.setStrokeThickness(strokeThickness);
1023 bool linesAreOpaque = !isPrinting && (!(decoration & TextDecorationUnderline) || underline.alpha() == 255) && (!(decoration & TextDecorationOverline) || overline.alpha() == 255) && (!(decoration & TextDecorationLineThrough) || linethrough.alpha() == 255);
1025 const RenderStyle& lineStyle = this->lineStyle();
1026 int baseline = lineStyle.fontMetrics().ascent();
1028 bool setClip = false;
1029 int extraOffset = 0;
1030 if (!linesAreOpaque && shadow && shadow->next()) {
1031 FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1032 for (const ShadowData* s = shadow; s; s = s->next()) {
1033 int shadowExtent = s->paintingExtent();
1034 FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1035 shadowRect.inflate(shadowExtent);
1036 int shadowX = isHorizontal() ? s->x() : s->y();
1037 int shadowY = isHorizontal() ? s->y() : -s->x();
1038 shadowRect.move(shadowX, shadowY);
1039 clipRect.unite(shadowRect);
1040 extraOffset = std::max(extraOffset, std::max(0, shadowY) + shadowExtent);
1043 context.clip(clipRect);
1044 extraOffset += baseline + 2;
1045 localOrigin.move(0, extraOffset);
1049 ColorSpace colorSpace = renderer().style().colorSpace();
1050 bool setShadow = false;
1054 if (!shadow->next()) {
1055 // The last set of lines paints normally inside the clip.
1056 localOrigin.move(0, -extraOffset);
1059 int shadowX = isHorizontal() ? shadow->x() : shadow->y();
1060 int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
1061 context.setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->radius(), shadow->color(), colorSpace);
1063 shadow = shadow->next();
1066 float wavyOffset = 2.f;
1068 context.setStrokeStyle(textDecorationStyleToStrokeStyle(decorationStyle));
1069 if (decoration & TextDecorationUnderline) {
1070 context.setStrokeColor(underline, colorSpace);
1071 TextUnderlinePosition underlinePosition = lineStyle.textUnderlinePosition();
1072 const int underlineOffset = computeUnderlineOffset(underlinePosition, lineStyle.fontMetrics(), this, textDecorationThickness);
1074 switch (decorationStyle) {
1075 case TextDecorationStyleWavy: {
1076 FloatPoint start(localOrigin.x(), localOrigin.y() + underlineOffset + wavyOffset);
1077 FloatPoint end(localOrigin.x() + width, localOrigin.y() + underlineOffset + wavyOffset);
1078 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1082 #if ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
1083 if ((lineStyle.textDecorationSkip() == TextDecorationSkipInk || lineStyle.textDecorationSkip() == TextDecorationSkipAuto) && isHorizontal()) {
1084 if (!context.paintingDisabled()) {
1085 drawSkipInkUnderline(textPainter, context, localOrigin, underlineOffset, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1088 // FIXME: Need to support text-decoration-skip: none.
1089 #endif // CSS3_TEXT_DECORATION_SKIP_INK
1090 context.drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + underlineOffset), width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1093 if (decoration & TextDecorationOverline) {
1094 context.setStrokeColor(overline, colorSpace);
1095 switch (decorationStyle) {
1096 case TextDecorationStyleWavy: {
1097 FloatPoint start(localOrigin.x(), localOrigin.y() - wavyOffset);
1098 FloatPoint end(localOrigin.x() + width, localOrigin.y() - wavyOffset);
1099 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1103 #if ENABLE(CSS3_TEXT_DECORATION_SKIP_INK)
1104 if ((lineStyle.textDecorationSkip() == TextDecorationSkipInk || lineStyle.textDecorationSkip() == TextDecorationSkipAuto) && isHorizontal()) {
1105 if (!context.paintingDisabled())
1106 drawSkipInkUnderline(textPainter, context, localOrigin, 0, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1108 // FIXME: Need to support text-decoration-skip: none.
1109 #endif // CSS3_TEXT_DECORATION_SKIP_INK
1110 context.drawLineForText(localOrigin, width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1113 if (decoration & TextDecorationLineThrough) {
1114 context.setStrokeColor(linethrough, colorSpace);
1115 switch (decorationStyle) {
1116 case TextDecorationStyleWavy: {
1117 FloatPoint start(localOrigin.x(), localOrigin.y() + 2 * baseline / 3);
1118 FloatPoint end(localOrigin.x() + width, localOrigin.y() + 2 * baseline / 3);
1119 strokeWavyTextDecoration(context, start, end, textDecorationThickness);
1123 context.drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting, decorationStyle == TextDecorationStyleDouble);
1131 context.clearShadow();
1134 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1136 switch (markerType) {
1137 case DocumentMarker::Spelling:
1138 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1139 case DocumentMarker::Grammar:
1140 return GraphicsContext::DocumentMarkerGrammarLineStyle;
1141 case DocumentMarker::CorrectionIndicator:
1142 return GraphicsContext::DocumentMarkerAutocorrectionReplacementLineStyle;
1143 case DocumentMarker::DictationAlternatives:
1144 return GraphicsContext::DocumentMarkerDictationAlternativesLineStyle;
1146 case DocumentMarker::DictationPhraseWithAlternatives:
1147 // FIXME: Rename TextCheckingDictationPhraseWithAlternativesLineStyle and remove the PLATFORM(IOS)-guard.
1148 return GraphicsContext::TextCheckingDictationPhraseWithAlternativesLineStyle;
1151 ASSERT_NOT_REACHED();
1152 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1156 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, const RenderStyle& style, const Font& font, bool grammar)
1158 // Never print spelling/grammar markers (5327887)
1159 if (renderer().document().printing())
1162 if (m_truncation == cFullTruncation)
1165 float start = 0; // start of line to draw, relative to tx
1166 float width = m_logicalWidth; // how much line to draw
1168 // Determine whether we need to measure text
1169 bool markerSpansWholeBox = true;
1170 if (m_start <= (int)marker->startOffset())
1171 markerSpansWholeBox = false;
1172 if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1173 markerSpansWholeBox = false;
1174 if (m_truncation != cNoTruncation)
1175 markerSpansWholeBox = false;
1177 bool isDictationMarker = marker->type() == DocumentMarker::DictationAlternatives;
1178 if (!markerSpansWholeBox || grammar || isDictationMarker) {
1179 int startPosition = std::max<int>(marker->startOffset() - m_start, 0);
1180 int endPosition = std::min<int>(marker->endOffset() - m_start, m_len);
1182 if (m_truncation != cNoTruncation)
1183 endPosition = std::min<int>(endPosition, m_truncation);
1185 // Calculate start & width
1186 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1187 int selHeight = selectionHeight();
1188 FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1189 TextRun run = constructTextRun(style, font);
1191 // FIXME: Convert the document markers to float rects.
1192 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1193 start = markerRect.x() - startPoint.x();
1194 width = markerRect.width();
1196 // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1197 // display a toolTip. We don't do this for misspelling markers.
1198 if (grammar || isDictationMarker) {
1199 markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1200 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1201 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1205 // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1206 // make sure to fit within those bounds. This means the top pixel(s) of the underline will overlap the
1207 // bottom pixel(s) of the glyphs in smaller font sizes. The alternatives are to increase the line spacing (bad!!)
1208 // or decrease the underline thickness. The overlap is actually the most useful, and matches what AppKit does.
1209 // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1210 // we pin to two pixels under the baseline.
1211 int lineThickness = cMisspellingLineThickness;
1212 int baseline = lineStyle().fontMetrics().ascent();
1213 int descent = logicalHeight() - baseline;
1214 int underlineOffset;
1215 if (descent <= (2 + lineThickness)) {
1216 // Place the underline at the very bottom of the text in small/medium fonts.
1217 underlineOffset = logicalHeight() - lineThickness;
1219 // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1220 underlineOffset = baseline + 2;
1222 pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1225 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, const RenderStyle& style, const Font& font)
1227 // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1228 // the same word there are no pieces sticking out.
1229 int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1230 int selHeight = selectionHeight();
1232 int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1233 int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1234 TextRun run = constructTextRun(style, font);
1236 // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1237 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1238 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1239 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1241 // Optionally highlight the text
1242 if (renderer().frame().editor().markedTextMatchesAreHighlighted()) {
1243 Color color = marker->activeMatch() ? renderer().theme().platformActiveTextSearchHighlightColor() : renderer().theme().platformInactiveTextSearchHighlightColor();
1244 GraphicsContextStateSaver stateSaver(*pt);
1245 updateGraphicsContext(*pt, TextPaintStyle(color, style.colorSpace())); // Don't draw text at all!
1246 pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1247 pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style.colorSpace(), sPos, ePos);
1251 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, const RenderStyle& style, const Font& font)
1253 // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
1254 int top = selectionTop();
1255 int h = selectionHeight();
1257 int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1258 int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1259 TextRun run = constructTextRun(style, font);
1260 IntPoint startPoint = IntPoint(x(), top);
1262 // Compute and store the rect associated with this marker.
1263 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, h, sPos, ePos));
1264 markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1265 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1268 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, const RenderStyle& style, const Font& font, bool background)
1270 if (!renderer().textNode())
1273 Vector<DocumentMarker*> markers = renderer().document().markers().markersFor(renderer().textNode());
1274 Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1276 // Give any document markers that touch this run a chance to draw before the text has been drawn.
1277 // Note end() points at the last char, not one past it like endOffset and ranges do.
1278 for ( ; markerIt != markers.end(); ++markerIt) {
1279 DocumentMarker* marker = *markerIt;
1281 // Paint either the background markers or the foreground markers, but not both
1282 switch (marker->type()) {
1283 case DocumentMarker::Grammar:
1284 case DocumentMarker::Spelling:
1285 case DocumentMarker::CorrectionIndicator:
1286 case DocumentMarker::Replacement:
1287 case DocumentMarker::DictationAlternatives:
1289 // FIXME: Remove the PLATFORM(IOS)-guard.
1290 case DocumentMarker::DictationPhraseWithAlternatives:
1295 case DocumentMarker::TextMatch:
1296 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1297 case DocumentMarker::TelephoneNumber:
1306 if (marker->endOffset() <= start())
1307 // marker is completely before this run. This might be a marker that sits before the
1308 // first run we draw, or markers that were within runs we skipped due to truncation.
1311 if (marker->startOffset() > end())
1312 // marker is completely after this run, bail. A later run will paint it.
1315 // marker intersects this run. Paint it.
1316 switch (marker->type()) {
1317 case DocumentMarker::Spelling:
1318 case DocumentMarker::CorrectionIndicator:
1319 case DocumentMarker::DictationAlternatives:
1320 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1322 case DocumentMarker::Grammar:
1323 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1326 // FIXME: See <rdar://problem/8933352>. Also, remove the PLATFORM(IOS)-guard.
1327 case DocumentMarker::DictationPhraseWithAlternatives:
1328 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1331 case DocumentMarker::TextMatch:
1332 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1334 case DocumentMarker::Replacement:
1335 computeRectForReplacementMarker(marker, style, font);
1337 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1338 case DocumentMarker::TelephoneNumber:
1342 ASSERT_NOT_REACHED();
1348 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1350 if (m_truncation == cFullTruncation)
1353 float start = 0; // start of line to draw, relative to tx
1354 float width = m_logicalWidth; // how much line to draw
1355 bool useWholeWidth = true;
1356 unsigned paintStart = m_start;
1357 unsigned paintEnd = end() + 1; // end points at the last char, not past it
1358 if (paintStart <= underline.startOffset) {
1359 paintStart = underline.startOffset;
1360 useWholeWidth = false;
1361 start = renderer().width(m_start, paintStart - m_start, textPos(), isFirstLine());
1363 if (paintEnd != underline.endOffset) { // end points at the last char, not past it
1364 paintEnd = std::min(paintEnd, (unsigned)underline.endOffset);
1365 useWholeWidth = false;
1367 if (m_truncation != cNoTruncation) {
1368 paintEnd = std::min(paintEnd, (unsigned)m_start + m_truncation);
1369 useWholeWidth = false;
1371 if (!useWholeWidth) {
1372 width = renderer().width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLine());
1375 // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1376 // All other marked text underlines are 1px thick.
1377 // If there's not enough space the underline will touch or overlap characters.
1378 int lineThickness = 1;
1379 int baseline = lineStyle().fontMetrics().ascent();
1380 if (underline.thick && logicalHeight() - baseline >= 2)
1383 // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1384 // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1388 ctx->setStrokeColor(underline.color, renderer().style().colorSpace());
1389 ctx->setStrokeThickness(lineThickness);
1390 ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, renderer().document().printing());
1393 int InlineTextBox::caretMinOffset() const
1398 int InlineTextBox::caretMaxOffset() const
1400 return m_start + m_len;
1403 float InlineTextBox::textPos() const
1405 // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1406 // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1407 if (logicalLeft() == 0)
1409 return logicalLeft() - root().logicalLeft();
1412 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1417 if (lineOffset - logicalLeft() > logicalWidth())
1418 return isLeftToRightDirection() ? len() : 0;
1419 if (lineOffset - logicalLeft() < 0)
1420 return isLeftToRightDirection() ? 0 : len();
1422 FontCachePurgePreventer fontCachePurgePreventer;
1424 const RenderStyle& lineStyle = this->lineStyle();
1425 const Font& font = fontToUse(lineStyle, renderer());
1426 return font.offsetForPosition(constructTextRun(lineStyle, font), lineOffset - logicalLeft(), includePartialGlyphs);
1429 float InlineTextBox::positionForOffset(int offset) const
1431 ASSERT(offset >= m_start);
1432 ASSERT(offset <= m_start + m_len);
1435 return logicalLeft();
1437 FontCachePurgePreventer fontCachePurgePreventer;
1439 const RenderStyle& lineStyle = this->lineStyle();
1440 const Font& font = fontToUse(lineStyle, renderer());
1441 int from = !isLeftToRightDirection() ? offset - m_start : 0;
1442 int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1443 // FIXME: Do we need to add rightBearing here?
1444 return font.selectionRectForText(constructTextRun(lineStyle, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1447 TextRun InlineTextBox::constructTextRun(const RenderStyle& style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1449 ASSERT(renderer().text());
1451 String string = renderer().text();
1452 unsigned startPos = start();
1453 unsigned length = len();
1455 if (string.length() != length || startPos)
1456 string = string.substringSharingImpl(startPos, length);
1458 return constructTextRun(style, font, string, renderer().textLength() - startPos, charactersWithHyphen);
1461 TextRun InlineTextBox::constructTextRun(const RenderStyle& style, const Font& font, String string, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1463 int length = string.length();
1465 if (charactersWithHyphen) {
1466 adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, string, length);
1467 maximumLength = length;
1470 ASSERT(maximumLength >= length);
1472 TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style.rtlOrdering() == VisualOrder, !renderer().canUseSimpleFontCodePath());
1473 run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
1474 if (font.isSVGFont())
1475 run.setRenderingContext(SVGTextRunRenderingContext::create(renderer()));
1477 // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1478 run.setCharactersLength(maximumLength);
1479 ASSERT(run.charactersLength() >= run.length());
1485 const char* InlineTextBox::boxName() const
1487 return "InlineTextBox";
1490 void InlineTextBox::showBox(int printedCharacters) const
1492 String value = renderer().text();
1493 value = value.substring(start(), len());
1494 value.replaceWithLiteral('\\', "\\\\");
1495 value.replaceWithLiteral('\n', "\\n");
1496 printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1497 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1499 printedCharacters = fprintf(stderr, "\t%s %p", renderer().renderName(), &renderer());
1500 const int rendererCharacterOffset = 24;
1501 for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1503 fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1508 } // namespace WebCore