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"
29 #include "DocumentMarkerController.h"
31 #include "EllipsisBox.h"
32 #include "FontCache.h"
34 #include "GraphicsContext.h"
35 #include "HitTestResult.h"
37 #include "PaintInfo.h"
38 #include "RenderedDocumentMarker.h"
39 #include "RenderArena.h"
41 #include "RenderBlock.h"
42 #include "RenderCombineText.h"
43 #include "RenderRubyRun.h"
44 #include "RenderRubyText.h"
45 #include "RenderTheme.h"
47 #include "SVGTextRunRenderingContext.h"
49 #include "break_lines.h"
50 #include <wtf/AlwaysInline.h>
51 #include <wtf/text/CString.h>
57 typedef WTF::HashMap<const InlineTextBox*, LayoutRect> InlineTextBoxOverflowMap;
58 static InlineTextBoxOverflowMap* gTextBoxesWithOverflow;
60 void InlineTextBox::destroy(RenderArena* arena)
62 if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
63 gTextBoxesWithOverflow->remove(this);
64 InlineBox::destroy(arena);
67 LayoutRect InlineTextBox::logicalOverflowRect() const
69 if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow)
70 return enclosingIntRect(logicalFrameRect());
71 return gTextBoxesWithOverflow->get(this);
74 void InlineTextBox::setLogicalOverflowRect(const LayoutRect& rect)
76 ASSERT(!knownToHaveNoOverflow());
77 if (!gTextBoxesWithOverflow)
78 gTextBoxesWithOverflow = new InlineTextBoxOverflowMap;
79 gTextBoxesWithOverflow->add(this, rect);
82 LayoutUnit InlineTextBox::baselinePosition(FontBaseline baselineType) const
84 if (!isText() || !parent())
86 if (parent()->renderer() == renderer()->parent())
87 return parent()->baselinePosition(baselineType);
88 return toRenderBoxModelObject(renderer()->parent())->baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
91 LayoutUnit InlineTextBox::lineHeight() const
93 if (!isText() || !renderer()->parent())
95 if (m_renderer->isBR())
96 return toRenderBR(m_renderer)->lineHeight(isFirstLineStyle());
97 if (parent()->renderer() == renderer()->parent())
98 return parent()->lineHeight();
99 return toRenderBoxModelObject(renderer()->parent())->lineHeight(isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
102 LayoutUnit InlineTextBox::selectionTop()
104 return root()->selectionTop();
107 LayoutUnit InlineTextBox::selectionBottom()
109 return root()->selectionBottom();
112 LayoutUnit InlineTextBox::selectionHeight()
114 return root()->selectionHeight();
117 bool InlineTextBox::isSelected(int startPos, int endPos) const
119 LayoutUnit sPos = max<LayoutUnit>(startPos - m_start, 0);
120 LayoutUnit ePos = min<LayoutUnit>(endPos - m_start, m_len);
121 return (sPos < ePos);
124 RenderObject::SelectionState InlineTextBox::selectionState()
126 RenderObject::SelectionState state = renderer()->selectionState();
127 if (state == RenderObject::SelectionStart || state == RenderObject::SelectionEnd || state == RenderObject::SelectionBoth) {
128 int startPos, endPos;
129 renderer()->selectionStartEnd(startPos, endPos);
130 // The position after a hard line break is considered to be past its end.
131 int lastSelectable = start() + len() - (isLineBreak() ? 1 : 0);
133 bool start = (state != RenderObject::SelectionEnd && startPos >= m_start && startPos < m_start + m_len);
134 bool end = (state != RenderObject::SelectionStart && endPos > m_start && endPos <= lastSelectable);
136 state = RenderObject::SelectionBoth;
138 state = RenderObject::SelectionStart;
140 state = RenderObject::SelectionEnd;
141 else if ((state == RenderObject::SelectionEnd || startPos < m_start) &&
142 (state == RenderObject::SelectionStart || endPos > lastSelectable))
143 state = RenderObject::SelectionInside;
144 else if (state == RenderObject::SelectionBoth)
145 state = RenderObject::SelectionNone;
148 // If there are ellipsis following, make sure their selection is updated.
149 if (m_truncation != cNoTruncation && root()->ellipsisBox()) {
150 EllipsisBox* ellipsis = root()->ellipsisBox();
151 if (state != RenderObject::SelectionNone) {
153 selectionStartEnd(start, end);
154 // The ellipsis should be considered to be selected if the end of
155 // the selection is past the beginning of the truncation and the
156 // beginning of the selection is before or at the beginning of the
158 ellipsis->setSelectionState(end >= m_truncation && start <= m_truncation ?
159 RenderObject::SelectionInside : RenderObject::SelectionNone);
161 ellipsis->setSelectionState(RenderObject::SelectionNone);
167 static void adjustCharactersAndLengthForHyphen(BufferForAppendingHyphen& charactersWithHyphen, RenderStyle* style, const UChar*& characters, int& length)
169 const AtomicString& hyphenString = style->hyphenString();
170 charactersWithHyphen.reserveCapacity(length + hyphenString.length());
171 charactersWithHyphen.append(characters, length);
172 charactersWithHyphen.append(hyphenString);
173 characters = charactersWithHyphen.characters();
174 length += hyphenString.length();
177 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos)
179 int sPos = max(startPos - m_start, 0);
180 int ePos = min(endPos - m_start, (int)m_len);
185 FontCachePurgePreventer fontCachePurgePreventer;
187 RenderText* textObj = textRenderer();
188 LayoutUnit selTop = selectionTop();
189 LayoutUnit selHeight = selectionHeight();
190 RenderStyle* styleToUse = textObj->style(isFirstLineStyle());
191 const Font& font = styleToUse->font();
193 BufferForAppendingHyphen charactersWithHyphen;
194 bool respectHyphen = ePos == m_len && hasHyphen();
195 TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
197 endPos = textRun.length();
199 LayoutRect r = enclosingIntRect(font.selectionRectForText(textRun, FloatPoint(logicalLeft(), selTop), selHeight, sPos, ePos));
201 LayoutUnit logicalWidth = r.width();
202 if (r.x() > logicalRight())
204 else if (r.maxX() > logicalRight())
205 logicalWidth = logicalRight() - r.x();
207 LayoutPoint topPoint = isHorizontal() ? LayoutPoint(r.x(), selTop) : LayoutPoint(selTop, r.x());
208 LayoutUnit width = isHorizontal() ? logicalWidth : selHeight;
209 LayoutUnit height = isHorizontal() ? selHeight : logicalWidth;
211 return LayoutRect(topPoint, LayoutSize(width, height));
214 void InlineTextBox::deleteLine(RenderArena* arena)
216 toRenderText(renderer())->removeTextBox(this);
220 void InlineTextBox::extractLine()
225 toRenderText(renderer())->extractTextBox(this);
228 void InlineTextBox::attachLine()
233 toRenderText(renderer())->attachTextBox(this);
236 float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, float visibleRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
239 m_truncation = cFullTruncation;
243 // For LTR this is the left edge of the box, for RTL, the right edge in parent coordinates.
244 float ellipsisX = flowIsLTR ? visibleRightEdge - ellipsisWidth : visibleLeftEdge + ellipsisWidth;
246 // Criteria for full truncation:
247 // LTR: the left edge of the ellipsis is to the left of our text run.
248 // RTL: the right edge of the ellipsis is to the right of our text run.
249 bool ltrFullTruncation = flowIsLTR && ellipsisX <= left();
250 bool rtlFullTruncation = !flowIsLTR && ellipsisX >= left() + logicalWidth();
251 if (ltrFullTruncation || rtlFullTruncation) {
252 // Too far. Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
253 m_truncation = cFullTruncation;
258 bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < right());
259 bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > left());
260 if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
263 // The inline box may have different directionality than it's parent. Since truncation
264 // behavior depends both on both the parent and the inline block's directionality, we
265 // must keep track of these separately.
266 bool ltr = isLeftToRightDirection();
267 if (ltr != flowIsLTR) {
268 // Width in pixels of the visible portion of the box, excluding the ellipsis.
269 int visibleBoxWidth = visibleRightEdge - visibleLeftEdge - ellipsisWidth;
270 ellipsisX = ltr ? left() + visibleBoxWidth : right() - visibleBoxWidth;
273 int offset = offsetForPosition(ellipsisX, false);
275 // No characters should be rendered. Set ourselves to full truncation and place the ellipsis at the min of our start
276 // and the ellipsis edge.
277 m_truncation = cFullTruncation;
278 truncatedWidth += ellipsisWidth;
279 return min(ellipsisX, x());
282 // Set the truncation index on the text run.
283 m_truncation = offset;
285 // If we got here that means that we were only partially truncated and we need to return the pixel offset at which
286 // to place the ellipsis.
287 float widthOfVisibleText = toRenderText(renderer())->width(m_start, offset, textPos(), isFirstLineStyle());
289 // The ellipsis needs to be placed just after the last visible character.
290 // Where "after" is defined by the flow directionality, not the inline
291 // box directionality.
292 // e.g. In the case of an LTR inline box truncated in an RTL flow then we can
293 // have a situation such as |Hello| -> |...He|
294 truncatedWidth += widthOfVisibleText + ellipsisWidth;
296 return left() + widthOfVisibleText;
298 return right() - widthOfVisibleText - ellipsisWidth;
300 truncatedWidth += logicalWidth();
304 Color correctedTextColor(Color textColor, Color backgroundColor)
306 // Adjust the text color if it is too close to the background color,
307 // by darkening or lightening it to move it further away.
309 int d = differenceSquared(textColor, backgroundColor);
310 // semi-arbitrarily chose 65025 (255^2) value here after a few tests;
315 int distanceFromWhite = differenceSquared(textColor, Color::white);
316 int distanceFromBlack = differenceSquared(textColor, Color::black);
318 if (distanceFromWhite < distanceFromBlack) {
319 return textColor.dark();
322 return textColor.light();
325 void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness, ColorSpace colorSpace)
327 TextDrawingModeFlags mode = context->textDrawingMode();
328 if (strokeThickness > 0) {
329 TextDrawingModeFlags newMode = mode | TextModeStroke;
330 if (mode != newMode) {
331 context->setTextDrawingMode(newMode);
336 if (mode & TextModeFill && (fillColor != context->fillColor() || colorSpace != context->fillColorSpace()))
337 context->setFillColor(fillColor, colorSpace);
339 if (mode & TextModeStroke) {
340 if (strokeColor != context->strokeColor())
341 context->setStrokeColor(strokeColor, colorSpace);
342 if (strokeThickness != context->strokeThickness())
343 context->setStrokeThickness(strokeThickness);
347 bool InlineTextBox::isLineBreak() const
349 return renderer()->isBR() || (renderer()->style()->preserveNewline() && len() == 1 && (*textRenderer()->text())[start()] == '\n');
352 bool InlineTextBox::nodeAtPoint(const HitTestRequest&, HitTestResult& result, const HitTestPoint& pointInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
357 FloatPoint boxOrigin = locationIncludingFlipping();
358 boxOrigin.moveBy(accumulatedOffset);
359 FloatRect rect(boxOrigin, size());
360 if (m_truncation != cFullTruncation && visibleToHitTesting() && pointInContainer.intersects(rect)) {
361 renderer()->updateHitTestResult(result, flipForWritingMode(pointInContainer.point() - toLayoutSize(accumulatedOffset)));
362 if (!result.addNodeToRectBasedTestResult(renderer()->node(), pointInContainer, rect))
368 FloatSize InlineTextBox::applyShadowToGraphicsContext(GraphicsContext* context, const ShadowData* shadow, const FloatRect& textRect, bool stroked, bool opaque, bool horizontal)
373 FloatSize extraOffset;
374 int shadowX = horizontal ? shadow->x() : shadow->y();
375 int shadowY = horizontal ? shadow->y() : -shadow->x();
376 FloatSize shadowOffset(shadowX, shadowY);
377 int shadowBlur = shadow->blur();
378 const Color& shadowColor = shadow->color();
380 if (shadow->next() || stroked || !opaque) {
381 FloatRect shadowRect(textRect);
382 shadowRect.inflate(shadowBlur);
383 shadowRect.move(shadowOffset);
385 context->clip(shadowRect);
387 extraOffset = FloatSize(0, 2 * textRect.height() + max(0.0f, shadowOffset.height()) + shadowBlur);
388 shadowOffset -= extraOffset;
391 context->setShadow(shadowOffset, shadowBlur, shadowColor, context->fillColorSpace());
395 static void paintTextWithShadows(GraphicsContext* context, const Font& font, const TextRun& textRun, const AtomicString& emphasisMark, int emphasisMarkOffset, int startOffset, int endOffset, int truncationPoint, const FloatPoint& textOrigin,
396 const FloatRect& boxRect, const ShadowData* shadow, bool stroked, bool horizontal)
398 Color fillColor = context->fillColor();
399 ColorSpace fillColorSpace = context->fillColorSpace();
400 bool opaque = fillColor.alpha() == 255;
402 context->setFillColor(Color::black, fillColorSpace);
407 extraOffset = roundedIntSize(InlineTextBox::applyShadowToGraphicsContext(context, shadow, boxRect, stroked, opaque, horizontal));
409 context->setFillColor(fillColor, fillColorSpace);
411 if (startOffset <= endOffset) {
412 if (emphasisMark.isEmpty())
413 context->drawText(font, textRun, textOrigin + extraOffset, startOffset, endOffset);
415 context->drawEmphasisMarks(font, textRun, emphasisMark, textOrigin + extraOffset + IntSize(0, emphasisMarkOffset), startOffset, endOffset);
418 if (emphasisMark.isEmpty())
419 context->drawText(font, textRun, textOrigin + extraOffset, 0, endOffset);
421 context->drawEmphasisMarks(font, textRun, emphasisMark, textOrigin + extraOffset + IntSize(0, emphasisMarkOffset), 0, endOffset);
422 } if (startOffset < truncationPoint) {
423 if (emphasisMark.isEmpty())
424 context->drawText(font, textRun, textOrigin + extraOffset, startOffset, truncationPoint);
426 context->drawEmphasisMarks(font, textRun, emphasisMark, textOrigin + extraOffset + IntSize(0, emphasisMarkOffset), startOffset, truncationPoint);
433 if (shadow->next() || stroked || !opaque)
436 context->clearShadow();
438 shadow = shadow->next();
439 } while (shadow || stroked || !opaque);
442 bool InlineTextBox::getEmphasisMarkPosition(RenderStyle* style, TextEmphasisPosition& emphasisPosition) const
444 // This function returns true if there are text emphasis marks and they are suppressed by ruby text.
445 if (style->textEmphasisMark() == TextEmphasisMarkNone)
448 emphasisPosition = style->textEmphasisPosition();
449 if (emphasisPosition == TextEmphasisPositionUnder)
450 return true; // Ruby text is always over, so it cannot suppress emphasis marks under.
452 RenderBlock* containingBlock = renderer()->containingBlock();
453 if (!containingBlock->isRubyBase())
454 return true; // This text is not inside a ruby base, so it does not have ruby text over it.
456 if (!containingBlock->parent()->isRubyRun())
457 return true; // Cannot get the ruby text.
459 RenderRubyText* rubyText = toRenderRubyRun(containingBlock->parent())->rubyText();
461 // The emphasis marks over are suppressed only if there is a ruby text box and it not empty.
462 return !rubyText || !rubyText->firstLineBox();
465 enum RotationDirection { Counterclockwise, Clockwise };
467 static inline AffineTransform rotation(const FloatRect& boxRect, RotationDirection clockwise)
469 return clockwise ? AffineTransform(0, 1, -1, 0, boxRect.x() + boxRect.maxY(), boxRect.maxY() - boxRect.x())
470 : AffineTransform(0, -1, 1, 0, boxRect.x() - boxRect.maxY(), boxRect.x() + boxRect.maxY());
473 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
475 if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE ||
476 m_truncation == cFullTruncation || paintInfo.phase == PaintPhaseOutline || !m_len)
479 ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
481 LayoutUnit logicalLeftSide = logicalLeftVisualOverflow();
482 LayoutUnit logicalRightSide = logicalRightVisualOverflow();
483 LayoutUnit logicalStart = logicalLeftSide + (isHorizontal() ? paintOffset.x() : paintOffset.y());
484 LayoutUnit logicalExtent = logicalRightSide - logicalLeftSide;
486 LayoutUnit paintEnd = isHorizontal() ? paintInfo.rect.maxX() : paintInfo.rect.maxY();
487 LayoutUnit paintStart = isHorizontal() ? paintInfo.rect.x() : paintInfo.rect.y();
489 LayoutPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
491 if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
494 bool isPrinting = textRenderer()->document()->printing();
496 // Determine whether or not we're selected.
497 bool haveSelection = !isPrinting && paintInfo.phase != PaintPhaseTextClip && selectionState() != RenderObject::SelectionNone;
498 if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
499 // When only painting the selection, don't bother to paint if there is none.
502 if (m_truncation != cNoTruncation) {
503 if (renderer()->containingBlock()->style()->isLeftToRightDirection() != isLeftToRightDirection()) {
504 // Make the visible fragment of text hug the edge closest to the rest of the run by moving the origin
505 // at which we start drawing text.
506 // e.g. In the case of LTR text truncated in an RTL Context, the correct behavior is:
507 // |Hello|CBA| -> |...He|CBA|
508 // In order to draw the fragment "He" aligned to the right edge of it's box, we need to start drawing
509 // farther to the right.
510 // NOTE: WebKit's behavior differs from that of IE which appears to just overlay the ellipsis on top of the
511 // truncated string i.e. |Hello|CBA| -> |...lo|CBA|
512 LayoutUnit widthOfVisibleText = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
513 LayoutUnit widthOfHiddenText = m_logicalWidth - widthOfVisibleText;
514 // FIXME: The hit testing logic also needs to take this translation into account.
515 LayoutSize truncationOffset(isLeftToRightDirection() ? widthOfHiddenText : -widthOfHiddenText, 0);
516 adjustedPaintOffset.move(isHorizontal() ? truncationOffset : truncationOffset.transposedSize());
520 GraphicsContext* context = paintInfo.context;
522 RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
524 adjustedPaintOffset.move(0, styleToUse->isHorizontalWritingMode() ? 0 : -logicalHeight());
526 FloatPoint boxOrigin = locationIncludingFlipping();
527 boxOrigin.move(adjustedPaintOffset.x(), adjustedPaintOffset.y());
528 FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
530 RenderCombineText* combinedText = styleToUse->hasTextCombine() && textRenderer()->isCombineText() && toRenderCombineText(textRenderer())->isCombined() ? toRenderCombineText(textRenderer()) : 0;
532 bool shouldRotate = !isHorizontal() && !combinedText;
534 context->concatCTM(rotation(boxRect, Clockwise));
536 // Determine whether or not we have composition underlines to draw.
537 bool containsComposition = renderer()->node() && renderer()->frame()->editor()->compositionNode() == renderer()->node();
538 bool useCustomUnderlines = containsComposition && renderer()->frame()->editor()->compositionUsesCustomUnderlines();
540 // Determine the text colors and selection colors.
542 Color textStrokeColor;
543 Color emphasisMarkColor;
544 float textStrokeWidth = styleToUse->textStrokeWidth();
545 const ShadowData* textShadow = paintInfo.forceBlackText ? 0 : styleToUse->textShadow();
547 if (paintInfo.forceBlackText) {
548 textFillColor = Color::black;
549 textStrokeColor = Color::black;
550 emphasisMarkColor = Color::black;
552 textFillColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextFillColor);
554 bool forceBackgroundToWhite = false;
556 if (styleToUse->printColorAdjust() == PrintColorAdjustEconomy)
557 forceBackgroundToWhite = true;
558 if (textRenderer()->document()->settings() && textRenderer()->document()->settings()->shouldPrintBackgrounds())
559 forceBackgroundToWhite = false;
562 // Make the text fill color legible against a white background
563 if (forceBackgroundToWhite)
564 textFillColor = correctedTextColor(textFillColor, Color::white);
566 textStrokeColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
568 // Make the text stroke color legible against a white background
569 if (forceBackgroundToWhite)
570 textStrokeColor = correctedTextColor(textStrokeColor, Color::white);
572 emphasisMarkColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextEmphasisColor);
574 // Make the text stroke color legible against a white background
575 if (forceBackgroundToWhite)
576 emphasisMarkColor = correctedTextColor(emphasisMarkColor, Color::white);
579 bool paintSelectedTextOnly = (paintInfo.phase == PaintPhaseSelection);
580 bool paintSelectedTextSeparately = false;
582 Color selectionFillColor = textFillColor;
583 Color selectionStrokeColor = textStrokeColor;
584 Color selectionEmphasisMarkColor = emphasisMarkColor;
585 float selectionStrokeWidth = textStrokeWidth;
586 const ShadowData* selectionShadow = textShadow;
588 // Check foreground color first.
589 Color foreground = paintInfo.forceBlackText ? Color::black : renderer()->selectionForegroundColor();
590 if (foreground.isValid() && foreground != selectionFillColor) {
591 if (!paintSelectedTextOnly)
592 paintSelectedTextSeparately = true;
593 selectionFillColor = foreground;
596 Color emphasisMarkForeground = paintInfo.forceBlackText ? Color::black : renderer()->selectionEmphasisMarkColor();
597 if (emphasisMarkForeground.isValid() && emphasisMarkForeground != selectionEmphasisMarkColor) {
598 if (!paintSelectedTextOnly)
599 paintSelectedTextSeparately = true;
600 selectionEmphasisMarkColor = emphasisMarkForeground;
603 if (RenderStyle* pseudoStyle = renderer()->getCachedPseudoStyle(SELECTION)) {
604 const ShadowData* shadow = paintInfo.forceBlackText ? 0 : pseudoStyle->textShadow();
605 if (shadow != selectionShadow) {
606 if (!paintSelectedTextOnly)
607 paintSelectedTextSeparately = true;
608 selectionShadow = shadow;
611 float strokeWidth = pseudoStyle->textStrokeWidth();
612 if (strokeWidth != selectionStrokeWidth) {
613 if (!paintSelectedTextOnly)
614 paintSelectedTextSeparately = true;
615 selectionStrokeWidth = strokeWidth;
618 Color stroke = paintInfo.forceBlackText ? Color::black : pseudoStyle->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
619 if (stroke != selectionStrokeColor) {
620 if (!paintSelectedTextOnly)
621 paintSelectedTextSeparately = true;
622 selectionStrokeColor = stroke;
628 const Font& font = styleToUse->font();
630 FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
633 combinedText->adjustTextOrigin(textOrigin, boxRect);
635 // 1. Paint backgrounds behind text if needed. Examples of such backgrounds include selection
636 // and composition underlines.
637 if (paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseTextClip && !isPrinting) {
639 // Custom highlighters go behind everything else.
640 if (styleToUse->highlight() != nullAtom && !context->paintingDisabled())
641 paintCustomHighlight(adjustedPaintOffset, styleToUse->highlight());
644 if (containsComposition && !useCustomUnderlines)
645 paintCompositionBackground(context, boxOrigin, styleToUse, font,
646 renderer()->frame()->editor()->compositionStart(),
647 renderer()->frame()->editor()->compositionEnd());
648 #if ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
649 else if (containsComposition && useCustomUnderlines) {
650 const Vector<CompositionUnderline>& underlines = renderer()->frame()->editor()->customCompositionUnderlines();
651 size_t numUnderlines = underlines.size();
653 for (size_t index = 0; index < numUnderlines; ++index) {
654 const CompositionUnderline& underline = underlines[index];
656 if (underline.endOffset <= start())
657 // underline is completely before this run. This might be an underline that sits
658 // before the first run we draw, or underlines that were within runs we skipped
659 // due to truncation.
662 if (underline.startOffset <= end()) {
663 // underline intersects this run. Paint the background of the underline.
664 paintCompositionUnderlineBackground(context, boxOrigin, styleToUse, font, underline);
666 if (underline.endOffset > end() + 1)
667 // underline also runs into the next run. Bail now, no more marker advancement.
670 // underline is completely after this run, bail. A later run will paint it.
676 paintDocumentMarkers(context, boxOrigin, styleToUse, font, true);
678 if (haveSelection && !useCustomUnderlines)
679 paintSelection(context, boxOrigin, styleToUse, font, selectionFillColor);
682 if (Frame* frame = renderer()->frame()) {
683 if (Page* page = frame->page()) {
684 // FIXME: Right now, InlineTextBoxes never call addRelevantUnpaintedObject() even though they might
685 // legitimately be unpainted if they are waiting on a slow-loading web font. We should fix that, and
686 // when we do, we will have to account for the fact the InlineTextBoxes do not always have unique
687 // renderers and Page currently relies on each unpainted object having a unique renderer.
688 if (paintInfo.phase == PaintPhaseForeground)
689 page->addRelevantRepaintedObject(renderer(), IntRect(boxOrigin.x(), boxOrigin.y(), logicalWidth(), logicalHeight()));
693 // 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
696 const UChar* characters;
698 characters = textRenderer()->text()->characters() + m_start;
699 maximumLength = textRenderer()->textLength() - m_start;
701 combinedText->charactersToRender(m_start, characters, length);
702 maximumLength = length;
705 BufferForAppendingHyphen charactersWithHyphen;
706 TextRun textRun = constructTextRun(styleToUse, font, characters, length, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
708 length = textRun.length();
712 if (paintSelectedTextOnly || paintSelectedTextSeparately)
713 selectionStartEnd(sPos, ePos);
715 if (m_truncation != cNoTruncation) {
716 sPos = min<int>(sPos, m_truncation);
717 ePos = min<int>(ePos, m_truncation);
718 length = m_truncation;
721 int emphasisMarkOffset = 0;
722 TextEmphasisPosition emphasisMarkPosition;
723 bool hasTextEmphasis = getEmphasisMarkPosition(styleToUse, emphasisMarkPosition);
724 const AtomicString& emphasisMark = hasTextEmphasis ? styleToUse->textEmphasisMarkString() : nullAtom;
725 if (!emphasisMark.isEmpty())
726 emphasisMarkOffset = emphasisMarkPosition == TextEmphasisPositionOver ? -font.fontMetrics().ascent() - font.emphasisMarkDescent(emphasisMark) : font.fontMetrics().descent() + font.emphasisMarkAscent(emphasisMark);
728 if (!paintSelectedTextOnly) {
729 // For stroked painting, we have to change the text drawing mode. It's probably dangerous to leave that mutated as a side
730 // effect, so only when we know we're stroking, do a save/restore.
731 GraphicsContextStateSaver stateSaver(*context, textStrokeWidth > 0);
733 updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
734 if (!paintSelectedTextSeparately || ePos <= sPos) {
735 // FIXME: Truncate right-to-left text correctly.
736 paintTextWithShadows(context, font, textRun, nullAtom, 0, 0, length, length, textOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
738 paintTextWithShadows(context, font, textRun, nullAtom, 0, ePos, sPos, length, textOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
740 if (!emphasisMark.isEmpty()) {
741 updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
743 DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
744 TextRun& emphasisMarkTextRun = combinedText ? objectReplacementCharacterTextRun : textRun;
745 FloatPoint emphasisMarkTextOrigin = combinedText ? FloatPoint(boxOrigin.x() + boxRect.width() / 2, boxOrigin.y() + font.fontMetrics().ascent()) : textOrigin;
747 context->concatCTM(rotation(boxRect, Clockwise));
749 if (!paintSelectedTextSeparately || ePos <= sPos) {
750 // FIXME: Truncate right-to-left text correctly.
751 paintTextWithShadows(context, combinedText ? combinedText->originalFont() : font, emphasisMarkTextRun, emphasisMark, emphasisMarkOffset, 0, length, length, emphasisMarkTextOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
753 paintTextWithShadows(context, combinedText ? combinedText->originalFont() : font, emphasisMarkTextRun, emphasisMark, emphasisMarkOffset, ePos, sPos, length, emphasisMarkTextOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
756 context->concatCTM(rotation(boxRect, Counterclockwise));
760 if ((paintSelectedTextOnly || paintSelectedTextSeparately) && sPos < ePos) {
761 // paint only the text that is selected
762 GraphicsContextStateSaver stateSaver(*context, selectionStrokeWidth > 0);
764 updateGraphicsContext(context, selectionFillColor, selectionStrokeColor, selectionStrokeWidth, styleToUse->colorSpace());
765 paintTextWithShadows(context, font, textRun, nullAtom, 0, sPos, ePos, length, textOrigin, boxRect, selectionShadow, selectionStrokeWidth > 0, isHorizontal());
766 if (!emphasisMark.isEmpty()) {
767 updateGraphicsContext(context, selectionEmphasisMarkColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
769 DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
770 TextRun& emphasisMarkTextRun = combinedText ? objectReplacementCharacterTextRun : textRun;
771 FloatPoint emphasisMarkTextOrigin = combinedText ? FloatPoint(boxOrigin.x() + boxRect.width() / 2, boxOrigin.y() + font.fontMetrics().ascent()) : textOrigin;
773 context->concatCTM(rotation(boxRect, Clockwise));
775 paintTextWithShadows(context, combinedText ? combinedText->originalFont() : font, emphasisMarkTextRun, emphasisMark, emphasisMarkOffset, sPos, ePos, length, emphasisMarkTextOrigin, boxRect, selectionShadow, selectionStrokeWidth > 0, isHorizontal());
778 context->concatCTM(rotation(boxRect, Counterclockwise));
783 int textDecorations = styleToUse->textDecorationsInEffect();
784 if (textDecorations != TDNONE && paintInfo.phase != PaintPhaseSelection) {
785 updateGraphicsContext(context, textFillColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
786 paintDecoration(context, boxOrigin, textDecorations, textShadow);
789 if (paintInfo.phase == PaintPhaseForeground) {
790 paintDocumentMarkers(context, boxOrigin, styleToUse, font, false);
792 if (useCustomUnderlines) {
793 const Vector<CompositionUnderline>& underlines = renderer()->frame()->editor()->customCompositionUnderlines();
794 size_t numUnderlines = underlines.size();
796 for (size_t index = 0; index < numUnderlines; ++index) {
797 const CompositionUnderline& underline = underlines[index];
799 if (underline.endOffset <= start())
800 // underline is completely before this run. This might be an underline that sits
801 // before the first run we draw, or underlines that were within runs we skipped
802 // due to truncation.
805 if (underline.startOffset <= end()) {
806 // underline intersects this run. Paint it.
807 paintCompositionUnderline(context, boxOrigin, underline);
808 if (underline.endOffset > end() + 1)
809 // underline also runs into the next run. Bail now, no more marker advancement.
812 // underline is completely after this run, bail. A later run will paint it.
819 context->concatCTM(rotation(boxRect, Counterclockwise));
822 void InlineTextBox::selectionStartEnd(int& sPos, int& ePos)
824 int startPos, endPos;
825 if (renderer()->selectionState() == RenderObject::SelectionInside) {
827 endPos = textRenderer()->textLength();
829 textRenderer()->selectionStartEnd(startPos, endPos);
830 if (renderer()->selectionState() == RenderObject::SelectionStart)
831 endPos = textRenderer()->textLength();
832 else if (renderer()->selectionState() == RenderObject::SelectionEnd)
836 sPos = max(startPos - m_start, 0);
837 ePos = min(endPos - m_start, (int)m_len);
840 void alignSelectionRectToDevicePixels(FloatRect& rect)
842 float maxX = floorf(rect.maxX());
843 rect.setX(floorf(rect.x()));
844 rect.setWidth(roundf(maxX - rect.x()));
847 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color textColor)
849 if (context->paintingDisabled())
852 // See if we have a selection to paint at all.
854 selectionStartEnd(sPos, ePos);
855 #if ENABLE(TIZEN_WEBKIT2_TEXT_SELECTION_NOT_PAINT_SELECTION_FOR_INPUTBOX)
856 Node* shadowAncestor = 0;
857 if (renderer() && renderer()->node())
858 shadowAncestor = renderer()->node()->shadowAncestorNode();
860 if (shadowAncestor && (shadowAncestor->renderer()->isTextField() || shadowAncestor->renderer()->isTextArea())) {
861 if (selectionState() != RenderObject::SelectionBoth) {
862 RenderObject* startObj = textRenderer()->view()->selectionStart();
863 RenderObject* endObj = textRenderer()->view()->selectionEnd();
864 if (!(startObj->node()->isInShadowTree() && endObj->node()->isInShadowTree()))
873 Color c = renderer()->selectionBackgroundColor();
874 if (!c.isValid() || c.alpha() == 0)
877 // If the text color ends up being the same as the selection background, invert the selection
880 c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
882 GraphicsContextStateSaver stateSaver(*context);
883 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
885 // If the text is truncated, let the thing being painted in the truncation
886 // draw its own highlight.
887 int length = m_truncation != cNoTruncation ? m_truncation : m_len;
888 const UChar* characters = textRenderer()->text()->characters() + m_start;
890 BufferForAppendingHyphen charactersWithHyphen;
891 bool respectHyphen = ePos == length && hasHyphen();
892 TextRun textRun = constructTextRun(style, font, characters, length, textRenderer()->textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
894 ePos = textRun.length();
896 LayoutUnit selectionBottom = root()->selectionBottom();
897 LayoutUnit selectionTop = root()->selectionTopAdjustedForPrecedingBlock();
899 int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
900 int selHeight = max(0, roundToInt(selectionBottom - selectionTop));
902 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
903 FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
904 alignSelectionRectToDevicePixels(clipRect);
906 context->clip(clipRect);
908 #if ENABLE(TIZEN_PAINT_SELECTION_ANTIALIAS_NONE)
909 bool antialias = context->shouldAntialias();
910 context->setShouldAntialias(false);
911 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
912 context->setShouldAntialias(antialias);
914 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
918 #if ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
919 void InlineTextBox::paintCompositionUnderlineBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, const CompositionUnderline underline)
921 int offset = m_start;
922 int sOffset = static_cast<int>(underline.startOffset);
923 int eOffset = static_cast<int>(underline.endOffset);
924 int length = static_cast<int>(m_len);
925 int sPos = max(sOffset - offset, 0);
926 int ePos = min(eOffset - offset, length);
931 GraphicsContextStateSaver stateSaver(*context);
933 Color c = underline.backgroundColor;
937 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
939 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
940 int selHeight = selectionHeight();
941 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
942 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
946 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, int startPos, int endPos)
948 int offset = m_start;
949 int sPos = max(startPos - offset, 0);
950 int ePos = min(endPos - offset, (int)m_len);
955 GraphicsContextStateSaver stateSaver(*context);
957 Color c = Color(225, 221, 85);
959 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
961 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
962 int selHeight = selectionHeight();
963 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
964 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
969 void InlineTextBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type)
971 Frame* frame = renderer()->frame();
974 Page* page = frame->page();
978 RootInlineBox* r = root();
979 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + selectionTop(), r->logicalWidth(), selectionHeight());
980 FloatRect textRect(paintOffset.x() + x(), rootRect.y(), logicalWidth(), rootRect.height());
982 page->chrome()->client()->paintCustomHighlight(renderer()->node(), type, textRect, rootRect, true, false);
987 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, int deco, const ShadowData* shadow)
989 if (m_truncation == cFullTruncation)
992 FloatPoint localOrigin = boxOrigin;
994 float width = m_logicalWidth;
995 if (m_truncation != cNoTruncation) {
996 width = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
997 if (!isLeftToRightDirection())
998 localOrigin.move(m_logicalWidth - width, 0);
1001 // Get the text decoration colors.
1002 Color underline, overline, linethrough;
1003 renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, isFirstLineStyle());
1005 // Use a special function for underlines to get the positioning exactly right.
1006 bool isPrinting = textRenderer()->document()->printing();
1007 context->setStrokeThickness(1.0f); // FIXME: We should improve this rule and not always just assume 1.
1009 bool linesAreOpaque = !isPrinting && (!(deco & UNDERLINE) || underline.alpha() == 255) && (!(deco & OVERLINE) || overline.alpha() == 255) && (!(deco & LINE_THROUGH) || linethrough.alpha() == 255);
1011 RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
1012 int baseline = styleToUse->fontMetrics().ascent();
1014 bool setClip = false;
1015 int extraOffset = 0;
1016 if (!linesAreOpaque && shadow && shadow->next()) {
1017 FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1018 for (const ShadowData* s = shadow; s; s = s->next()) {
1019 FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1020 shadowRect.inflate(s->blur());
1021 int shadowX = isHorizontal() ? s->x() : s->y();
1022 int shadowY = isHorizontal() ? s->y() : -s->x();
1023 shadowRect.move(shadowX, shadowY);
1024 clipRect.unite(shadowRect);
1025 extraOffset = max(extraOffset, max(0, shadowY) + s->blur());
1028 context->clip(clipRect);
1029 extraOffset += baseline + 2;
1030 localOrigin.move(0, extraOffset);
1034 ColorSpace colorSpace = renderer()->style()->colorSpace();
1035 bool setShadow = false;
1039 if (!shadow->next()) {
1040 // The last set of lines paints normally inside the clip.
1041 localOrigin.move(0, -extraOffset);
1044 int shadowX = isHorizontal() ? shadow->x() : shadow->y();
1045 int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
1046 context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color(), colorSpace);
1048 shadow = shadow->next();
1051 if (deco & UNDERLINE) {
1052 context->setStrokeColor(underline, colorSpace);
1053 context->setStrokeStyle(SolidStroke);
1054 // Leave one pixel of white between the baseline and the underline.
1055 context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + baseline + 1), width, isPrinting);
1057 if (deco & OVERLINE) {
1058 context->setStrokeColor(overline, colorSpace);
1059 context->setStrokeStyle(SolidStroke);
1060 context->drawLineForText(localOrigin, width, isPrinting);
1062 if (deco & LINE_THROUGH) {
1063 context->setStrokeColor(linethrough, colorSpace);
1064 context->setStrokeStyle(SolidStroke);
1065 context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting);
1072 context->clearShadow();
1075 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1077 switch (markerType) {
1078 case DocumentMarker::Spelling:
1079 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1080 case DocumentMarker::Grammar:
1081 return GraphicsContext::DocumentMarkerGrammarLineStyle;
1082 case DocumentMarker::CorrectionIndicator:
1083 return GraphicsContext::DocumentMarkerAutocorrectionReplacementLineStyle;
1084 case DocumentMarker::DictationAlternatives:
1085 return GraphicsContext::DocumentMarkerDictationAlternativesLineStyle;
1087 ASSERT_NOT_REACHED();
1088 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1092 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1094 // Never print spelling/grammar markers (5327887)
1095 if (textRenderer()->document()->printing())
1098 if (m_truncation == cFullTruncation)
1101 float start = 0; // start of line to draw, relative to tx
1102 float width = m_logicalWidth; // how much line to draw
1104 // Determine whether we need to measure text
1105 bool markerSpansWholeBox = true;
1106 if (m_start <= (int)marker->startOffset())
1107 markerSpansWholeBox = false;
1108 if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1109 markerSpansWholeBox = false;
1110 if (m_truncation != cNoTruncation)
1111 markerSpansWholeBox = false;
1113 bool isDictationMarker = marker->type() == DocumentMarker::DictationAlternatives;
1114 if (!markerSpansWholeBox || grammar || isDictationMarker) {
1115 int startPosition = max<int>(marker->startOffset() - m_start, 0);
1116 int endPosition = min<int>(marker->endOffset() - m_start, m_len);
1118 if (m_truncation != cNoTruncation)
1119 endPosition = min<int>(endPosition, m_truncation);
1121 // Calculate start & width
1122 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1123 int selHeight = selectionHeight();
1124 FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1125 TextRun run = constructTextRun(style, font);
1127 // FIXME: Convert the document markers to float rects.
1128 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1129 start = markerRect.x() - startPoint.x();
1130 width = markerRect.width();
1132 // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1133 // display a toolTip. We don't do this for misspelling markers.
1134 if (grammar || isDictationMarker) {
1135 markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1136 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1137 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1141 // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1142 // make sure to fit within those bounds. This means the top pixel(s) of the underline will overlap the
1143 // bottom pixel(s) of the glyphs in smaller font sizes. The alternatives are to increase the line spacing (bad!!)
1144 // or decrease the underline thickness. The overlap is actually the most useful, and matches what AppKit does.
1145 // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1146 // we pin to two pixels under the baseline.
1147 int lineThickness = cMisspellingLineThickness;
1148 int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1149 int descent = logicalHeight() - baseline;
1150 int underlineOffset;
1151 if (descent <= (2 + lineThickness)) {
1152 // Place the underline at the very bottom of the text in small/medium fonts.
1153 underlineOffset = logicalHeight() - lineThickness;
1155 // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1156 underlineOffset = baseline + 2;
1158 pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1161 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1163 // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1164 // the same word there are no pieces sticking out.
1165 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1166 int selHeight = selectionHeight();
1168 int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1169 int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1170 TextRun run = constructTextRun(style, font);
1172 // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1173 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1174 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1175 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1177 // Optionally highlight the text
1178 if (renderer()->frame()->editor()->markedTextMatchesAreHighlighted()) {
1179 Color color = marker->activeMatch() ?
1180 renderer()->theme()->platformActiveTextSearchHighlightColor() :
1181 renderer()->theme()->platformInactiveTextSearchHighlightColor();
1182 GraphicsContextStateSaver stateSaver(*pt);
1183 updateGraphicsContext(pt, color, color, 0, style->colorSpace()); // Don't draw text at all!
1184 pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1185 pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style->colorSpace(), sPos, ePos);
1189 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, RenderStyle* style, const Font& font)
1191 // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
1192 int top = selectionTop();
1193 int h = selectionHeight();
1195 int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1196 int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1197 TextRun run = constructTextRun(style, font);
1198 IntPoint startPoint = IntPoint(x(), top);
1200 // Compute and store the rect associated with this marker.
1201 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, h, sPos, ePos));
1202 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1203 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1206 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1208 if (!renderer()->node())
1211 Vector<DocumentMarker*> markers = renderer()->document()->markers()->markersFor(renderer()->node());
1212 Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1214 // Give any document markers that touch this run a chance to draw before the text has been drawn.
1215 // Note end() points at the last char, not one past it like endOffset and ranges do.
1216 for ( ; markerIt != markers.end(); markerIt++) {
1217 DocumentMarker* marker = *markerIt;
1219 // Paint either the background markers or the foreground markers, but not both
1220 switch (marker->type()) {
1221 case DocumentMarker::Grammar:
1222 case DocumentMarker::Spelling:
1223 case DocumentMarker::CorrectionIndicator:
1224 case DocumentMarker::Replacement:
1225 case DocumentMarker::DictationAlternatives:
1229 case DocumentMarker::TextMatch:
1237 if (marker->endOffset() <= start())
1238 // marker is completely before this run. This might be a marker that sits before the
1239 // first run we draw, or markers that were within runs we skipped due to truncation.
1242 if (marker->startOffset() > end())
1243 // marker is completely after this run, bail. A later run will paint it.
1246 // marker intersects this run. Paint it.
1247 switch (marker->type()) {
1248 case DocumentMarker::Spelling:
1249 case DocumentMarker::CorrectionIndicator:
1250 case DocumentMarker::DictationAlternatives:
1251 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1253 case DocumentMarker::Grammar:
1254 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1256 case DocumentMarker::TextMatch:
1257 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1259 case DocumentMarker::Replacement:
1260 computeRectForReplacementMarker(marker, style, font);
1263 ASSERT_NOT_REACHED();
1269 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1271 if (m_truncation == cFullTruncation)
1274 float start = 0; // start of line to draw, relative to tx
1275 float width = m_logicalWidth; // how much line to draw
1276 bool useWholeWidth = true;
1277 unsigned paintStart = m_start;
1278 unsigned paintEnd = end() + 1; // end points at the last char, not past it
1279 if (paintStart <= underline.startOffset) {
1280 paintStart = underline.startOffset;
1281 useWholeWidth = false;
1282 start = toRenderText(renderer())->width(m_start, paintStart - m_start, textPos(), isFirstLineStyle());
1284 if (paintEnd != underline.endOffset) { // end points at the last char, not past it
1285 paintEnd = min(paintEnd, (unsigned)underline.endOffset);
1286 useWholeWidth = false;
1288 if (m_truncation != cNoTruncation) {
1289 paintEnd = min(paintEnd, (unsigned)m_start + m_truncation);
1290 useWholeWidth = false;
1292 if (!useWholeWidth) {
1293 width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLineStyle());
1296 // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1297 // All other marked text underlines are 1px thick.
1298 // If there's not enough space the underline will touch or overlap characters.
1299 int lineThickness = 1;
1300 int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1301 if (underline.thick && logicalHeight() - baseline >= 2)
1304 #if !ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
1305 // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1306 // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1312 ctx->setStrokeColor(underline.color, renderer()->style()->colorSpace());
1313 ctx->setStrokeThickness(lineThickness);
1314 ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document()->printing());
1317 int InlineTextBox::caretMinOffset() const
1322 int InlineTextBox::caretMaxOffset() const
1324 return m_start + m_len;
1327 float InlineTextBox::textPos() const
1329 // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1330 // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1331 if (logicalLeft() == 0)
1333 return logicalLeft() - root()->logicalLeft();
1336 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1341 if (lineOffset - logicalLeft() > logicalWidth())
1342 return isLeftToRightDirection() ? len() : 0;
1343 if (lineOffset - logicalLeft() < 0)
1344 return isLeftToRightDirection() ? 0 : len();
1346 FontCachePurgePreventer fontCachePurgePreventer;
1348 RenderText* text = toRenderText(renderer());
1349 RenderStyle* style = text->style(isFirstLineStyle());
1350 const Font& font = style->font();
1351 return font.offsetForPosition(constructTextRun(style, font), lineOffset - logicalLeft(), includePartialGlyphs);
1354 float InlineTextBox::positionForOffset(int offset) const
1356 ASSERT(offset >= m_start);
1357 ASSERT(offset <= m_start + m_len);
1360 return logicalLeft();
1362 FontCachePurgePreventer fontCachePurgePreventer;
1364 RenderText* text = toRenderText(renderer());
1365 RenderStyle* styleToUse = text->style(isFirstLineStyle());
1367 const Font& font = styleToUse->font();
1368 int from = !isLeftToRightDirection() ? offset - m_start : 0;
1369 int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1370 // FIXME: Do we need to add rightBearing here?
1371 return font.selectionRectForText(constructTextRun(styleToUse, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1374 bool InlineTextBox::containsCaretOffset(int offset) const
1376 // Offsets before the box are never "in".
1377 if (offset < m_start)
1380 int pastEnd = m_start + m_len;
1382 // Offsets inside the box (not at either edge) are always "in".
1383 if (offset < pastEnd)
1386 // Offsets outside the box are always "out".
1387 if (offset > pastEnd)
1390 // Offsets at the end are "out" for line breaks (they are on the next line).
1394 // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1398 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1402 RenderText* textRenderer = this->textRenderer();
1403 ASSERT(textRenderer);
1404 ASSERT(textRenderer->characters());
1406 return constructTextRun(style, font, textRenderer->characters() + start(), len(), textRenderer->textLength() - start(), charactersWithHyphen);
1409 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, const UChar* characters, int length, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1413 RenderText* textRenderer = this->textRenderer();
1414 ASSERT(textRenderer);
1416 if (charactersWithHyphen) {
1417 adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, characters, length);
1418 maximumLength = length;
1421 ASSERT(maximumLength >= length);
1423 TextRun run(characters, length, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !textRenderer->canUseSimpleFontCodePath());
1424 run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
1425 if (textRunNeedsRenderingContext(font))
1426 run.setRenderingContext(SVGTextRunRenderingContext::create(textRenderer));
1428 // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1429 run.setCharactersLength(maximumLength);
1430 ASSERT(run.charactersLength() >= run.length());
1436 const char* InlineTextBox::boxName() const
1438 return "InlineTextBox";
1441 void InlineTextBox::showBox(int printedCharacters) const
1443 const RenderText* obj = toRenderText(renderer());
1444 String value = obj->text();
1445 value = value.substring(start(), len());
1446 value.replaceWithLiteral('\\', "\\\\");
1447 value.replaceWithLiteral('\n', "\\n");
1448 printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1449 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1451 printedCharacters = fprintf(stderr, "\t%s %p", obj->renderName(), obj);
1452 const int rendererCharacterOffset = 24;
1453 for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1455 fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1460 } // namespace WebCore