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);
858 Color c = renderer()->selectionBackgroundColor();
859 if (!c.isValid() || c.alpha() == 0)
862 // If the text color ends up being the same as the selection background, invert the selection
865 c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
867 GraphicsContextStateSaver stateSaver(*context);
868 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
870 // If the text is truncated, let the thing being painted in the truncation
871 // draw its own highlight.
872 int length = m_truncation != cNoTruncation ? m_truncation : m_len;
873 const UChar* characters = textRenderer()->text()->characters() + m_start;
875 BufferForAppendingHyphen charactersWithHyphen;
876 bool respectHyphen = ePos == length && hasHyphen();
877 TextRun textRun = constructTextRun(style, font, characters, length, textRenderer()->textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
879 ePos = textRun.length();
881 LayoutUnit selectionBottom = root()->selectionBottom();
882 LayoutUnit selectionTop = root()->selectionTopAdjustedForPrecedingBlock();
884 int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
885 int selHeight = max(0, roundToInt(selectionBottom - selectionTop));
887 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
888 FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
889 alignSelectionRectToDevicePixels(clipRect);
891 context->clip(clipRect);
893 #if ENABLE(TIZEN_PAINT_SELECTION_ANTIALIAS_NONE)
894 bool antialias = context->shouldAntialias();
895 context->setShouldAntialias(false);
896 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
897 context->setShouldAntialias(antialias);
899 context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
903 #if ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
904 void InlineTextBox::paintCompositionUnderlineBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, const CompositionUnderline underline)
906 int offset = m_start;
907 int sOffset = static_cast<int>(underline.startOffset);
908 int eOffset = static_cast<int>(underline.endOffset);
909 int length = static_cast<int>(m_len);
910 int sPos = max(sOffset - offset, 0);
911 int ePos = min(eOffset - offset, length);
916 GraphicsContextStateSaver stateSaver(*context);
918 Color c = underline.backgroundColor;
922 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
924 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
925 int selHeight = selectionHeight();
926 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
927 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
931 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, int startPos, int endPos)
933 int offset = m_start;
934 int sPos = max(startPos - offset, 0);
935 int ePos = min(endPos - offset, (int)m_len);
940 GraphicsContextStateSaver stateSaver(*context);
942 Color c = Color(225, 221, 85);
944 updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
946 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
947 int selHeight = selectionHeight();
948 FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
949 context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
954 void InlineTextBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type)
956 Frame* frame = renderer()->frame();
959 Page* page = frame->page();
963 RootInlineBox* r = root();
964 FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + selectionTop(), r->logicalWidth(), selectionHeight());
965 FloatRect textRect(paintOffset.x() + x(), rootRect.y(), logicalWidth(), rootRect.height());
967 page->chrome()->client()->paintCustomHighlight(renderer()->node(), type, textRect, rootRect, true, false);
972 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, int deco, const ShadowData* shadow)
974 if (m_truncation == cFullTruncation)
977 FloatPoint localOrigin = boxOrigin;
979 float width = m_logicalWidth;
980 if (m_truncation != cNoTruncation) {
981 width = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
982 if (!isLeftToRightDirection())
983 localOrigin.move(m_logicalWidth - width, 0);
986 // Get the text decoration colors.
987 Color underline, overline, linethrough;
988 renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, isFirstLineStyle());
990 // Use a special function for underlines to get the positioning exactly right.
991 bool isPrinting = textRenderer()->document()->printing();
992 context->setStrokeThickness(1.0f); // FIXME: We should improve this rule and not always just assume 1.
994 bool linesAreOpaque = !isPrinting && (!(deco & UNDERLINE) || underline.alpha() == 255) && (!(deco & OVERLINE) || overline.alpha() == 255) && (!(deco & LINE_THROUGH) || linethrough.alpha() == 255);
996 RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
997 int baseline = styleToUse->fontMetrics().ascent();
999 bool setClip = false;
1000 int extraOffset = 0;
1001 if (!linesAreOpaque && shadow && shadow->next()) {
1002 FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1003 for (const ShadowData* s = shadow; s; s = s->next()) {
1004 FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1005 shadowRect.inflate(s->blur());
1006 int shadowX = isHorizontal() ? s->x() : s->y();
1007 int shadowY = isHorizontal() ? s->y() : -s->x();
1008 shadowRect.move(shadowX, shadowY);
1009 clipRect.unite(shadowRect);
1010 extraOffset = max(extraOffset, max(0, shadowY) + s->blur());
1013 context->clip(clipRect);
1014 extraOffset += baseline + 2;
1015 localOrigin.move(0, extraOffset);
1019 ColorSpace colorSpace = renderer()->style()->colorSpace();
1020 bool setShadow = false;
1024 if (!shadow->next()) {
1025 // The last set of lines paints normally inside the clip.
1026 localOrigin.move(0, -extraOffset);
1029 int shadowX = isHorizontal() ? shadow->x() : shadow->y();
1030 int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
1031 context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color(), colorSpace);
1033 shadow = shadow->next();
1036 if (deco & UNDERLINE) {
1037 context->setStrokeColor(underline, colorSpace);
1038 context->setStrokeStyle(SolidStroke);
1039 // Leave one pixel of white between the baseline and the underline.
1040 context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + baseline + 1), width, isPrinting);
1042 if (deco & OVERLINE) {
1043 context->setStrokeColor(overline, colorSpace);
1044 context->setStrokeStyle(SolidStroke);
1045 context->drawLineForText(localOrigin, width, isPrinting);
1047 if (deco & LINE_THROUGH) {
1048 context->setStrokeColor(linethrough, colorSpace);
1049 context->setStrokeStyle(SolidStroke);
1050 context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting);
1057 context->clearShadow();
1060 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1062 switch (markerType) {
1063 case DocumentMarker::Spelling:
1064 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1065 case DocumentMarker::Grammar:
1066 return GraphicsContext::DocumentMarkerGrammarLineStyle;
1067 case DocumentMarker::CorrectionIndicator:
1068 return GraphicsContext::DocumentMarkerAutocorrectionReplacementLineStyle;
1069 case DocumentMarker::DictationAlternatives:
1070 return GraphicsContext::DocumentMarkerDictationAlternativesLineStyle;
1072 ASSERT_NOT_REACHED();
1073 return GraphicsContext::DocumentMarkerSpellingLineStyle;
1077 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1079 // Never print spelling/grammar markers (5327887)
1080 if (textRenderer()->document()->printing())
1083 if (m_truncation == cFullTruncation)
1086 float start = 0; // start of line to draw, relative to tx
1087 float width = m_logicalWidth; // how much line to draw
1089 // Determine whether we need to measure text
1090 bool markerSpansWholeBox = true;
1091 if (m_start <= (int)marker->startOffset())
1092 markerSpansWholeBox = false;
1093 if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1094 markerSpansWholeBox = false;
1095 if (m_truncation != cNoTruncation)
1096 markerSpansWholeBox = false;
1098 bool isDictationMarker = marker->type() == DocumentMarker::DictationAlternatives;
1099 if (!markerSpansWholeBox || grammar || isDictationMarker) {
1100 int startPosition = max<int>(marker->startOffset() - m_start, 0);
1101 int endPosition = min<int>(marker->endOffset() - m_start, m_len);
1103 if (m_truncation != cNoTruncation)
1104 endPosition = min<int>(endPosition, m_truncation);
1106 // Calculate start & width
1107 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1108 int selHeight = selectionHeight();
1109 FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1110 TextRun run = constructTextRun(style, font);
1112 // FIXME: Convert the document markers to float rects.
1113 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1114 start = markerRect.x() - startPoint.x();
1115 width = markerRect.width();
1117 // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1118 // display a toolTip. We don't do this for misspelling markers.
1119 if (grammar || isDictationMarker) {
1120 markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1121 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1122 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1126 // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1127 // make sure to fit within those bounds. This means the top pixel(s) of the underline will overlap the
1128 // bottom pixel(s) of the glyphs in smaller font sizes. The alternatives are to increase the line spacing (bad!!)
1129 // or decrease the underline thickness. The overlap is actually the most useful, and matches what AppKit does.
1130 // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1131 // we pin to two pixels under the baseline.
1132 int lineThickness = cMisspellingLineThickness;
1133 int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1134 int descent = logicalHeight() - baseline;
1135 int underlineOffset;
1136 if (descent <= (2 + lineThickness)) {
1137 // Place the underline at the very bottom of the text in small/medium fonts.
1138 underlineOffset = logicalHeight() - lineThickness;
1140 // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1141 underlineOffset = baseline + 2;
1143 pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1146 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1148 // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1149 // the same word there are no pieces sticking out.
1150 int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1151 int selHeight = selectionHeight();
1153 int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1154 int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1155 TextRun run = constructTextRun(style, font);
1157 // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1158 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1159 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1160 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1162 // Optionally highlight the text
1163 if (renderer()->frame()->editor()->markedTextMatchesAreHighlighted()) {
1164 Color color = marker->activeMatch() ?
1165 renderer()->theme()->platformActiveTextSearchHighlightColor() :
1166 renderer()->theme()->platformInactiveTextSearchHighlightColor();
1167 GraphicsContextStateSaver stateSaver(*pt);
1168 updateGraphicsContext(pt, color, color, 0, style->colorSpace()); // Don't draw text at all!
1169 pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1170 pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style->colorSpace(), sPos, ePos);
1174 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, RenderStyle* style, const Font& font)
1176 // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
1177 int top = selectionTop();
1178 int h = selectionHeight();
1180 int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1181 int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1182 TextRun run = constructTextRun(style, font);
1183 IntPoint startPoint = IntPoint(x(), top);
1185 // Compute and store the rect associated with this marker.
1186 IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, h, sPos, ePos));
1187 markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1188 toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1191 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1193 if (!renderer()->node())
1196 Vector<DocumentMarker*> markers = renderer()->document()->markers()->markersFor(renderer()->node());
1197 Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1199 // Give any document markers that touch this run a chance to draw before the text has been drawn.
1200 // Note end() points at the last char, not one past it like endOffset and ranges do.
1201 for ( ; markerIt != markers.end(); markerIt++) {
1202 DocumentMarker* marker = *markerIt;
1204 // Paint either the background markers or the foreground markers, but not both
1205 switch (marker->type()) {
1206 case DocumentMarker::Grammar:
1207 case DocumentMarker::Spelling:
1208 case DocumentMarker::CorrectionIndicator:
1209 case DocumentMarker::Replacement:
1210 case DocumentMarker::DictationAlternatives:
1214 case DocumentMarker::TextMatch:
1222 if (marker->endOffset() <= start())
1223 // marker is completely before this run. This might be a marker that sits before the
1224 // first run we draw, or markers that were within runs we skipped due to truncation.
1227 if (marker->startOffset() > end())
1228 // marker is completely after this run, bail. A later run will paint it.
1231 // marker intersects this run. Paint it.
1232 switch (marker->type()) {
1233 case DocumentMarker::Spelling:
1234 case DocumentMarker::CorrectionIndicator:
1235 case DocumentMarker::DictationAlternatives:
1236 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1238 case DocumentMarker::Grammar:
1239 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1241 case DocumentMarker::TextMatch:
1242 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1244 case DocumentMarker::Replacement:
1245 computeRectForReplacementMarker(marker, style, font);
1248 ASSERT_NOT_REACHED();
1254 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1256 if (m_truncation == cFullTruncation)
1259 float start = 0; // start of line to draw, relative to tx
1260 float width = m_logicalWidth; // how much line to draw
1261 bool useWholeWidth = true;
1262 unsigned paintStart = m_start;
1263 unsigned paintEnd = end() + 1; // end points at the last char, not past it
1264 if (paintStart <= underline.startOffset) {
1265 paintStart = underline.startOffset;
1266 useWholeWidth = false;
1267 start = toRenderText(renderer())->width(m_start, paintStart - m_start, textPos(), isFirstLineStyle());
1269 if (paintEnd != underline.endOffset) { // end points at the last char, not past it
1270 paintEnd = min(paintEnd, (unsigned)underline.endOffset);
1271 useWholeWidth = false;
1273 if (m_truncation != cNoTruncation) {
1274 paintEnd = min(paintEnd, (unsigned)m_start + m_truncation);
1275 useWholeWidth = false;
1277 if (!useWholeWidth) {
1278 width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLineStyle());
1281 // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1282 // All other marked text underlines are 1px thick.
1283 // If there's not enough space the underline will touch or overlap characters.
1284 int lineThickness = 1;
1285 int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1286 if (underline.thick && logicalHeight() - baseline >= 2)
1289 #if !ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
1290 // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1291 // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1297 ctx->setStrokeColor(underline.color, renderer()->style()->colorSpace());
1298 ctx->setStrokeThickness(lineThickness);
1299 ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document()->printing());
1302 int InlineTextBox::caretMinOffset() const
1307 int InlineTextBox::caretMaxOffset() const
1309 return m_start + m_len;
1312 float InlineTextBox::textPos() const
1314 // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1315 // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1316 if (logicalLeft() == 0)
1318 return logicalLeft() - root()->logicalLeft();
1321 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1326 if (lineOffset - logicalLeft() > logicalWidth())
1327 return isLeftToRightDirection() ? len() : 0;
1328 if (lineOffset - logicalLeft() < 0)
1329 return isLeftToRightDirection() ? 0 : len();
1331 FontCachePurgePreventer fontCachePurgePreventer;
1333 RenderText* text = toRenderText(renderer());
1334 RenderStyle* style = text->style(isFirstLineStyle());
1335 const Font& font = style->font();
1336 return font.offsetForPosition(constructTextRun(style, font), lineOffset - logicalLeft(), includePartialGlyphs);
1339 float InlineTextBox::positionForOffset(int offset) const
1341 ASSERT(offset >= m_start);
1342 ASSERT(offset <= m_start + m_len);
1345 return logicalLeft();
1347 FontCachePurgePreventer fontCachePurgePreventer;
1349 RenderText* text = toRenderText(renderer());
1350 RenderStyle* styleToUse = text->style(isFirstLineStyle());
1352 const Font& font = styleToUse->font();
1353 int from = !isLeftToRightDirection() ? offset - m_start : 0;
1354 int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1355 // FIXME: Do we need to add rightBearing here?
1356 return font.selectionRectForText(constructTextRun(styleToUse, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1359 bool InlineTextBox::containsCaretOffset(int offset) const
1361 // Offsets before the box are never "in".
1362 if (offset < m_start)
1365 int pastEnd = m_start + m_len;
1367 // Offsets inside the box (not at either edge) are always "in".
1368 if (offset < pastEnd)
1371 // Offsets outside the box are always "out".
1372 if (offset > pastEnd)
1375 // Offsets at the end are "out" for line breaks (they are on the next line).
1379 // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1383 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1387 RenderText* textRenderer = this->textRenderer();
1388 ASSERT(textRenderer);
1389 ASSERT(textRenderer->characters());
1391 return constructTextRun(style, font, textRenderer->characters() + start(), len(), textRenderer->textLength() - start(), charactersWithHyphen);
1394 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, const UChar* characters, int length, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1398 RenderText* textRenderer = this->textRenderer();
1399 ASSERT(textRenderer);
1401 if (charactersWithHyphen) {
1402 adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, characters, length);
1403 maximumLength = length;
1406 ASSERT(maximumLength >= length);
1408 TextRun run(characters, length, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !textRenderer->canUseSimpleFontCodePath());
1409 run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
1410 if (textRunNeedsRenderingContext(font))
1411 run.setRenderingContext(SVGTextRunRenderingContext::create(textRenderer));
1413 // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1414 run.setCharactersLength(maximumLength);
1415 ASSERT(run.charactersLength() >= run.length());
1421 const char* InlineTextBox::boxName() const
1423 return "InlineTextBox";
1426 void InlineTextBox::showBox(int printedCharacters) const
1428 const RenderText* obj = toRenderText(renderer());
1429 String value = obj->text();
1430 value = value.substring(start(), len());
1431 value.replaceWithLiteral('\\', "\\\\");
1432 value.replaceWithLiteral('\n', "\\n");
1433 printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1434 for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1436 printedCharacters = fprintf(stderr, "\t%s %p", obj->renderName(), obj);
1437 const int rendererCharacterOffset = 24;
1438 for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1440 fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1445 } // namespace WebCore