Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / InlineTextBox.cpp
1 /*
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.
5  *
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.
10  *
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.
15  *
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.
20  *
21  */
22
23 #include "config.h"
24 #include "core/rendering/InlineTextBox.h"
25
26 #include "core/dom/Document.h"
27 #include "core/dom/DocumentMarkerController.h"
28 #include "core/dom/RenderedDocumentMarker.h"
29 #include "core/dom/Text.h"
30 #include "core/editing/CompositionUnderline.h"
31 #include "core/editing/CompositionUnderlineRangeFilter.h"
32 #include "core/editing/Editor.h"
33 #include "core/editing/InputMethodController.h"
34 #include "core/frame/LocalFrame.h"
35 #include "core/page/Page.h"
36 #include "core/frame/Settings.h"
37 #include "core/rendering/AbstractInlineTextBox.h"
38 #include "core/rendering/EllipsisBox.h"
39 #include "core/rendering/HitTestResult.h"
40 #include "core/rendering/PaintInfo.h"
41 #include "core/rendering/RenderBR.h"
42 #include "core/rendering/RenderBlock.h"
43 #include "core/rendering/RenderCombineText.h"
44 #include "core/rendering/RenderRubyRun.h"
45 #include "core/rendering/RenderRubyText.h"
46 #include "core/rendering/RenderTheme.h"
47 #include "core/rendering/style/ShadowList.h"
48 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
49 #include "platform/RuntimeEnabledFeatures.h"
50 #include "platform/fonts/FontCache.h"
51 #include "platform/fonts/GlyphBuffer.h"
52 #include "platform/fonts/WidthIterator.h"
53 #include "platform/graphics/GraphicsContextStateSaver.h"
54 #include "wtf/Vector.h"
55 #include "wtf/text/CString.h"
56 #include "wtf/text/StringBuilder.h"
57
58 #include <algorithm>
59
60 namespace blink {
61
62 struct SameSizeAsInlineTextBox : public InlineBox {
63     unsigned variables[1];
64     unsigned short variables2[2];
65     void* pointers[2];
66 };
67
68 COMPILE_ASSERT(sizeof(InlineTextBox) == sizeof(SameSizeAsInlineTextBox), InlineTextBox_should_stay_small);
69
70 typedef WTF::HashMap<const InlineTextBox*, LayoutRect> InlineTextBoxOverflowMap;
71 static InlineTextBoxOverflowMap* gTextBoxesWithOverflow;
72
73 static const int misspellingLineThickness = 3;
74
75 void InlineTextBox::destroy()
76 {
77     AbstractInlineTextBox::willDestroy(this);
78
79     if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
80         gTextBoxesWithOverflow->remove(this);
81     InlineBox::destroy();
82 }
83
84 void InlineTextBox::markDirty()
85 {
86     m_len = 0;
87     m_start = 0;
88     InlineBox::markDirty();
89 }
90
91 LayoutRect InlineTextBox::logicalOverflowRect() const
92 {
93     if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow)
94         return enclosingIntRect(logicalFrameRect());
95     return gTextBoxesWithOverflow->get(this);
96 }
97
98 void InlineTextBox::setLogicalOverflowRect(const LayoutRect& rect)
99 {
100     ASSERT(!knownToHaveNoOverflow());
101     if (!gTextBoxesWithOverflow)
102         gTextBoxesWithOverflow = new InlineTextBoxOverflowMap;
103     gTextBoxesWithOverflow->add(this, rect);
104 }
105
106 int InlineTextBox::baselinePosition(FontBaseline baselineType) const
107 {
108     if (!isText() || !parent())
109         return 0;
110     if (parent()->renderer() == renderer().parent())
111         return parent()->baselinePosition(baselineType);
112     return toRenderBoxModelObject(renderer().parent())->baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
113 }
114
115 LayoutUnit InlineTextBox::lineHeight() const
116 {
117     if (!isText() || !renderer().parent())
118         return 0;
119     if (renderer().isBR())
120         return toRenderBR(renderer()).lineHeight(isFirstLineStyle());
121     if (parent()->renderer() == renderer().parent())
122         return parent()->lineHeight();
123     return toRenderBoxModelObject(renderer().parent())->lineHeight(isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
124 }
125
126 LayoutUnit InlineTextBox::selectionTop()
127 {
128     return root().selectionTop();
129 }
130
131 LayoutUnit InlineTextBox::selectionBottom()
132 {
133     return root().selectionBottom();
134 }
135
136 LayoutUnit InlineTextBox::selectionHeight()
137 {
138     return root().selectionHeight();
139 }
140
141 bool InlineTextBox::isSelected(int startPos, int endPos) const
142 {
143     int sPos = std::max(startPos - m_start, 0);
144     // The position after a hard line break is considered to be past its end.
145     // See the corresponding code in InlineTextBox::selectionState.
146     int ePos = std::min(endPos - m_start, int(m_len) + (isLineBreak() ? 0 : 1));
147     return (sPos < ePos);
148 }
149
150 RenderObject::SelectionState InlineTextBox::selectionState()
151 {
152     RenderObject::SelectionState state = renderer().selectionState();
153     if (state == RenderObject::SelectionStart || state == RenderObject::SelectionEnd || state == RenderObject::SelectionBoth) {
154         int startPos, endPos;
155         renderer().selectionStartEnd(startPos, endPos);
156         // The position after a hard line break is considered to be past its end.
157         // See the corresponding code in InlineTextBox::isSelected.
158         int lastSelectable = start() + len() - (isLineBreak() ? 1 : 0);
159
160         // FIXME: Remove -webkit-line-break: LineBreakAfterWhiteSpace.
161         int endOfLineAdjustmentForCSSLineBreak = renderer().style()->lineBreak() == LineBreakAfterWhiteSpace ? -1 : 0;
162         bool start = (state != RenderObject::SelectionEnd && startPos >= m_start && startPos <= m_start + m_len + endOfLineAdjustmentForCSSLineBreak);
163         bool end = (state != RenderObject::SelectionStart && endPos > m_start && endPos <= lastSelectable);
164         if (start && end)
165             state = RenderObject::SelectionBoth;
166         else if (start)
167             state = RenderObject::SelectionStart;
168         else if (end)
169             state = RenderObject::SelectionEnd;
170         else if ((state == RenderObject::SelectionEnd || startPos < m_start) &&
171                  (state == RenderObject::SelectionStart || endPos > lastSelectable))
172             state = RenderObject::SelectionInside;
173         else if (state == RenderObject::SelectionBoth)
174             state = RenderObject::SelectionNone;
175     }
176
177     // If there are ellipsis following, make sure their selection is updated.
178     if (m_truncation != cNoTruncation && root().ellipsisBox()) {
179         EllipsisBox* ellipsis = root().ellipsisBox();
180         if (state != RenderObject::SelectionNone) {
181             int start, end;
182             selectionStartEnd(start, end);
183             // The ellipsis should be considered to be selected if the end of
184             // the selection is past the beginning of the truncation and the
185             // beginning of the selection is before or at the beginning of the
186             // truncation.
187             ellipsis->setSelectionState(end >= m_truncation && start <= m_truncation ?
188                 RenderObject::SelectionInside : RenderObject::SelectionNone);
189         } else
190             ellipsis->setSelectionState(RenderObject::SelectionNone);
191     }
192
193     return state;
194 }
195
196 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos)
197 {
198     int sPos = std::max(startPos - m_start, 0);
199     int ePos = std::min(endPos - m_start, (int)m_len);
200
201     if (sPos > ePos)
202         return LayoutRect();
203
204     FontCachePurgePreventer fontCachePurgePreventer;
205
206     LayoutUnit selTop = selectionTop();
207     LayoutUnit selHeight = selectionHeight();
208     RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
209     const Font& font = styleToUse->font();
210
211     StringBuilder charactersWithHyphen;
212     bool respectHyphen = ePos == m_len && hasHyphen();
213     TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
214
215     FloatPoint startingPoint = FloatPoint(logicalLeft(), selTop.toFloat());
216     LayoutRect r;
217     if (sPos || ePos != static_cast<int>(m_len))
218         r = enclosingIntRect(font.selectionRectForText(textRun, startingPoint, selHeight, sPos, ePos));
219     else // Avoid computing the font width when the entire line box is selected as an optimization.
220         r = enclosingIntRect(FloatRect(startingPoint, FloatSize(m_logicalWidth, selHeight.toFloat())));
221
222     LayoutUnit logicalWidth = r.width();
223     if (r.x() > logicalRight())
224         logicalWidth  = 0;
225     else if (r.maxX() > logicalRight())
226         logicalWidth = logicalRight() - r.x();
227
228     LayoutPoint topPoint = isHorizontal() ? LayoutPoint(r.x(), selTop) : LayoutPoint(selTop, r.x());
229     LayoutUnit width = isHorizontal() ? logicalWidth : selHeight;
230     LayoutUnit height = isHorizontal() ? selHeight : logicalWidth;
231
232     return LayoutRect(topPoint, LayoutSize(width, height));
233 }
234
235 void InlineTextBox::deleteLine()
236 {
237     renderer().removeTextBox(this);
238     destroy();
239 }
240
241 void InlineTextBox::extractLine()
242 {
243     if (extracted())
244         return;
245
246     renderer().extractTextBox(this);
247 }
248
249 void InlineTextBox::attachLine()
250 {
251     if (!extracted())
252         return;
253
254     renderer().attachTextBox(this);
255 }
256
257 float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, float visibleRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
258 {
259     if (foundBox) {
260         m_truncation = cFullTruncation;
261         return -1;
262     }
263
264     // For LTR this is the left edge of the box, for RTL, the right edge in parent coordinates.
265     float ellipsisX = flowIsLTR ? visibleRightEdge - ellipsisWidth : visibleLeftEdge + ellipsisWidth;
266
267     // Criteria for full truncation:
268     // LTR: the left edge of the ellipsis is to the left of our text run.
269     // RTL: the right edge of the ellipsis is to the right of our text run.
270     bool ltrFullTruncation = flowIsLTR && ellipsisX <= logicalLeft();
271     bool rtlFullTruncation = !flowIsLTR && ellipsisX >= logicalLeft() + logicalWidth();
272     if (ltrFullTruncation || rtlFullTruncation) {
273         // Too far.  Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
274         m_truncation = cFullTruncation;
275         foundBox = true;
276         return -1;
277     }
278
279     bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < logicalRight());
280     bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > logicalLeft());
281     if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
282         foundBox = true;
283
284         // The inline box may have different directionality than it's parent.  Since truncation
285         // behavior depends both on both the parent and the inline block's directionality, we
286         // must keep track of these separately.
287         bool ltr = isLeftToRightDirection();
288         if (ltr != flowIsLTR) {
289             // Width in pixels of the visible portion of the box, excluding the ellipsis.
290             int visibleBoxWidth = visibleRightEdge - visibleLeftEdge  - ellipsisWidth;
291             ellipsisX = ltr ? logicalLeft() + visibleBoxWidth : logicalRight() - visibleBoxWidth;
292         }
293
294         int offset = offsetForPosition(ellipsisX, false);
295         if (offset == 0) {
296             // No characters should be rendered.  Set ourselves to full truncation and place the ellipsis at the min of our start
297             // and the ellipsis edge.
298             m_truncation = cFullTruncation;
299             truncatedWidth += ellipsisWidth;
300             return std::min(ellipsisX, logicalLeft());
301         }
302
303         // Set the truncation index on the text run.
304         m_truncation = offset;
305
306         // If we got here that means that we were only partially truncated and we need to return the pixel offset at which
307         // to place the ellipsis.
308         float widthOfVisibleText = renderer().width(m_start, offset, textPos(), flowIsLTR ? LTR : RTL, isFirstLineStyle());
309
310         // The ellipsis needs to be placed just after the last visible character.
311         // Where "after" is defined by the flow directionality, not the inline
312         // box directionality.
313         // e.g. In the case of an LTR inline box truncated in an RTL flow then we can
314         // have a situation such as |Hello| -> |...He|
315         truncatedWidth += widthOfVisibleText + ellipsisWidth;
316         if (flowIsLTR)
317             return logicalLeft() + widthOfVisibleText;
318         else
319             return logicalRight() - widthOfVisibleText - ellipsisWidth;
320     }
321     truncatedWidth += logicalWidth();
322     return -1;
323 }
324
325 static Color textColorForWhiteBackground(Color textColor)
326 {
327     int distanceFromWhite = differenceSquared(textColor, Color::white);
328     // semi-arbitrarily chose 65025 (255^2) value here after a few tests;
329     return distanceFromWhite > 65025 ? textColor : textColor.dark();
330 }
331
332 static void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness)
333 {
334     TextDrawingModeFlags mode = context->textDrawingMode();
335     if (strokeThickness > 0) {
336         TextDrawingModeFlags newMode = mode | TextModeStroke;
337         if (mode != newMode) {
338             context->setTextDrawingMode(newMode);
339             mode = newMode;
340         }
341     }
342
343     if (mode & TextModeFill && fillColor != context->fillColor())
344         context->setFillColor(fillColor);
345
346     if (mode & TextModeStroke) {
347         if (strokeColor != context->strokeColor())
348             context->setStrokeColor(strokeColor);
349         if (strokeThickness != context->strokeThickness())
350             context->setStrokeThickness(strokeThickness);
351     }
352 }
353
354 bool InlineTextBox::isLineBreak() const
355 {
356     return renderer().isBR() || (renderer().style()->preserveNewline() && len() == 1 && (*renderer().text().impl())[start()] == '\n');
357 }
358
359 bool InlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
360 {
361     if (isLineBreak())
362         return false;
363
364     FloatPoint boxOrigin = locationIncludingFlipping();
365     boxOrigin.moveBy(accumulatedOffset);
366     FloatRect rect(boxOrigin, size());
367     if (m_truncation != cFullTruncation && visibleToHitTestRequest(request) && locationInContainer.intersects(rect)) {
368         renderer().updateHitTestResult(result, flipForWritingMode(locationInContainer.point() - toLayoutSize(accumulatedOffset)));
369         if (!result.addNodeToRectBasedTestResult(renderer().node(), request, locationInContainer, rect))
370             return true;
371     }
372     return false;
373 }
374
375 static void paintTextWithShadows(GraphicsContext* context,
376     const Font& font, const TextRun& textRun,
377     const AtomicString& emphasisMark, int emphasisMarkOffset,
378     int startOffset, int endOffset, int truncationPoint,
379     const FloatPoint& textOrigin, const FloatRect& boxRect,
380     const ShadowList* shadowList, bool horizontal)
381 {
382     // Text shadows are disabled when printing. http://crbug.com/258321
383     bool hasShadow = shadowList && !context->printing();
384     if (hasShadow)
385         context->setDrawLooper(shadowList->createDrawLooper(DrawLooperBuilder::ShadowIgnoresAlpha, horizontal));
386
387     TextRunPaintInfo textRunPaintInfo(textRun);
388     textRunPaintInfo.bounds = boxRect;
389     if (startOffset <= endOffset) {
390         textRunPaintInfo.from = startOffset;
391         textRunPaintInfo.to = endOffset;
392         if (emphasisMark.isEmpty())
393             context->drawText(font, textRunPaintInfo, textOrigin);
394         else
395             context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
396     } else {
397         if (endOffset > 0) {
398             textRunPaintInfo.from = 0;
399             textRunPaintInfo.to = endOffset;
400             if (emphasisMark.isEmpty())
401                 context->drawText(font, textRunPaintInfo, textOrigin);
402             else
403                 context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
404         }
405         if (startOffset < truncationPoint) {
406             textRunPaintInfo.from = startOffset;
407             textRunPaintInfo.to = truncationPoint;
408             if (emphasisMark.isEmpty())
409                 context->drawText(font, textRunPaintInfo, textOrigin);
410             else
411                 context->drawEmphasisMarks(font, textRunPaintInfo, emphasisMark, textOrigin + IntSize(0, emphasisMarkOffset));
412         }
413     }
414
415     if (hasShadow)
416         context->clearDrawLooper();
417 }
418
419 static void paintEmphasisMark(GraphicsContext* context,
420     const AtomicString& emphasisMark, int emphasisMarkOffset,
421     int startOffset, int endOffset, int paintRunLength,
422     const Font& font, Color emphasisMarkColor, Color textStrokeColor, float textStrokeWidth, const ShadowList* textShadow,
423     RenderCombineText* combinedText, const TextRun& textRun,
424     const FloatPoint& textOrigin, const FloatRect& boxRect, bool horizontal)
425 {
426     ASSERT(!emphasisMark.isEmpty());
427     updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth);
428
429     if (combinedText) {
430         DEFINE_STATIC_LOCAL(TextRun, objectReplacementCharacterTextRun, (&objectReplacementCharacter, 1));
431         FloatPoint emphasisMarkTextOrigin(boxRect.x() + boxRect.width() / 2, boxRect.y() + font.fontMetrics().ascent());
432         context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Clockwise));
433         paintTextWithShadows(context, combinedText->originalFont(), objectReplacementCharacterTextRun, emphasisMark, emphasisMarkOffset, 0, 1, 1, emphasisMarkTextOrigin, boxRect, textShadow, horizontal);
434         context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Counterclockwise));
435     } else {
436         paintTextWithShadows(context, font, textRun, emphasisMark, emphasisMarkOffset, startOffset, endOffset, paintRunLength, textOrigin, boxRect, textShadow, horizontal);
437     }
438 }
439
440 bool InlineTextBox::getEmphasisMarkPosition(RenderStyle* style, TextEmphasisPosition& emphasisPosition) const
441 {
442     // This function returns true if there are text emphasis marks and they are suppressed by ruby text.
443     if (style->textEmphasisMark() == TextEmphasisMarkNone)
444         return false;
445
446     emphasisPosition = style->textEmphasisPosition();
447     if (emphasisPosition == TextEmphasisPositionUnder)
448         return true; // Ruby text is always over, so it cannot suppress emphasis marks under.
449
450     RenderBlock* containingBlock = renderer().containingBlock();
451     if (!containingBlock->isRubyBase())
452         return true; // This text is not inside a ruby base, so it does not have ruby text over it.
453
454     if (!containingBlock->parent()->isRubyRun())
455         return true; // Cannot get the ruby text.
456
457     RenderRubyText* rubyText = toRenderRubyRun(containingBlock->parent())->rubyText();
458
459     // The emphasis marks over are suppressed only if there is a ruby text box and it not empty.
460     return !rubyText || !rubyText->firstLineBox();
461 }
462
463 namespace {
464
465 struct TextPaintingStyle {
466     Color fillColor;
467     Color strokeColor;
468     Color emphasisMarkColor;
469     float strokeWidth;
470     const ShadowList* shadow;
471
472     bool operator==(const TextPaintingStyle& other)
473     {
474         return fillColor == other.fillColor
475             && strokeColor == other.strokeColor
476             && emphasisMarkColor == other.emphasisMarkColor
477             && strokeWidth == other.strokeWidth
478             && shadow == other.shadow;
479     }
480     bool operator!=(const TextPaintingStyle& other) { return !(*this == other); }
481 };
482
483 TextPaintingStyle textPaintingStyle(RenderText& renderer, RenderStyle* style, bool forceBlackText, bool isPrinting)
484 {
485     TextPaintingStyle textStyle;
486
487     if (forceBlackText) {
488         textStyle.fillColor = Color::black;
489         textStyle.strokeColor = Color::black;
490         textStyle.emphasisMarkColor = Color::black;
491         textStyle.strokeWidth = style->textStrokeWidth();
492         textStyle.shadow = 0;
493     } else {
494         textStyle.fillColor = renderer.resolveColor(style, CSSPropertyWebkitTextFillColor);
495         textStyle.strokeColor = renderer.resolveColor(style, CSSPropertyWebkitTextStrokeColor);
496         textStyle.emphasisMarkColor = renderer.resolveColor(style, CSSPropertyWebkitTextEmphasisColor);
497         textStyle.strokeWidth = style->textStrokeWidth();
498         textStyle.shadow = style->textShadow();
499
500         // Adjust text color when printing with a white background.
501         bool forceBackgroundToWhite = false;
502         if (isPrinting) {
503             if (style->printColorAdjust() == PrintColorAdjustEconomy)
504                 forceBackgroundToWhite = true;
505             if (renderer.document().settings() && renderer.document().settings()->shouldPrintBackgrounds())
506                 forceBackgroundToWhite = false;
507         }
508         if (forceBackgroundToWhite) {
509             textStyle.fillColor = textColorForWhiteBackground(textStyle.fillColor);
510             textStyle.strokeColor = textColorForWhiteBackground(textStyle.strokeColor);
511             textStyle.emphasisMarkColor = textColorForWhiteBackground(textStyle.emphasisMarkColor);
512         }
513
514         // Text shadows are disabled when printing. http://crbug.com/258321
515         if (isPrinting)
516             textStyle.shadow = 0;
517     }
518
519     return textStyle;
520 }
521
522 TextPaintingStyle selectionPaintingStyle(RenderText& renderer, bool haveSelection, bool forceBlackText, bool isPrinting, const TextPaintingStyle& textStyle)
523 {
524     TextPaintingStyle selectionStyle = textStyle;
525
526     if (haveSelection) {
527         if (!forceBlackText) {
528             selectionStyle.fillColor = renderer.selectionForegroundColor();
529             selectionStyle.emphasisMarkColor = renderer.selectionEmphasisMarkColor();
530         }
531
532         if (RenderStyle* pseudoStyle = renderer.getCachedPseudoStyle(SELECTION)) {
533             selectionStyle.strokeColor = forceBlackText ? Color::black : renderer.resolveColor(pseudoStyle, CSSPropertyWebkitTextStrokeColor);
534             selectionStyle.strokeWidth = pseudoStyle->textStrokeWidth();
535             selectionStyle.shadow = forceBlackText ? 0 : pseudoStyle->textShadow();
536         }
537
538         // Text shadows are disabled when printing. http://crbug.com/258321
539         if (isPrinting)
540             selectionStyle.shadow = 0;
541     }
542
543     return selectionStyle;
544 }
545
546 } // namespace
547
548 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
549 {
550     if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(&renderer()) || renderer().style()->visibility() != VISIBLE
551         || m_truncation == cFullTruncation || paintInfo.phase == PaintPhaseOutline || !m_len)
552         return;
553
554     ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
555
556     LayoutRect logicalVisualOverflow = logicalOverflowRect();
557     LayoutUnit logicalStart = logicalVisualOverflow.x() + (isHorizontal() ? paintOffset.x() : paintOffset.y());
558     LayoutUnit logicalExtent = logicalVisualOverflow.width();
559
560     LayoutUnit paintEnd = isHorizontal() ? paintInfo.rect.maxX() : paintInfo.rect.maxY();
561     LayoutUnit paintStart = isHorizontal() ? paintInfo.rect.x() : paintInfo.rect.y();
562
563     // When subpixel font scaling is enabled text runs are positioned at
564     // subpixel boundaries on the x-axis and thus there is no reason to
565     // snap the x value. We still round the y-axis to ensure consistent
566     // line heights.
567     LayoutPoint adjustedPaintOffset = RuntimeEnabledFeatures::subpixelFontScalingEnabled()
568         ? LayoutPoint(paintOffset.x(), paintOffset.y().round())
569         : roundedIntPoint(paintOffset);
570
571     if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
572         return;
573
574     bool isPrinting = renderer().document().printing();
575
576     // Determine whether or not we're selected.
577     bool haveSelection = !isPrinting && paintInfo.phase != PaintPhaseTextClip && selectionState() != RenderObject::SelectionNone;
578     if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
579         // When only painting the selection, don't bother to paint if there is none.
580         return;
581
582     if (m_truncation != cNoTruncation) {
583         if (renderer().containingBlock()->style()->isLeftToRightDirection() != isLeftToRightDirection()) {
584             // Make the visible fragment of text hug the edge closest to the rest of the run by moving the origin
585             // at which we start drawing text.
586             // e.g. In the case of LTR text truncated in an RTL Context, the correct behavior is:
587             // |Hello|CBA| -> |...He|CBA|
588             // In order to draw the fragment "He" aligned to the right edge of it's box, we need to start drawing
589             // farther to the right.
590             // NOTE: WebKit's behavior differs from that of IE which appears to just overlay the ellipsis on top of the
591             // truncated string i.e.  |Hello|CBA| -> |...lo|CBA|
592             LayoutUnit widthOfVisibleText = renderer().width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
593             LayoutUnit widthOfHiddenText = m_logicalWidth - widthOfVisibleText;
594             // FIXME: The hit testing logic also needs to take this translation into account.
595             LayoutSize truncationOffset(isLeftToRightDirection() ? widthOfHiddenText : -widthOfHiddenText, 0);
596             adjustedPaintOffset.move(isHorizontal() ? truncationOffset : truncationOffset.transposedSize());
597         }
598     }
599
600     GraphicsContext* context = paintInfo.context;
601     RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
602
603     adjustedPaintOffset.move(0, styleToUse->isHorizontalWritingMode() ? 0 : -logicalHeight());
604
605     FloatPoint boxOrigin = locationIncludingFlipping();
606     boxOrigin.move(adjustedPaintOffset.x().toFloat(), adjustedPaintOffset.y().toFloat());
607     FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
608
609     RenderCombineText* combinedText = styleToUse->hasTextCombine() && renderer().isCombineText() && toRenderCombineText(renderer()).isCombined() ? &toRenderCombineText(renderer()) : 0;
610
611     bool shouldRotate = !isHorizontal() && !combinedText;
612     if (shouldRotate)
613         context->concatCTM(rotation(boxRect, Clockwise));
614
615     // Determine whether or not we have composition underlines to draw.
616     bool containsComposition = renderer().node() && renderer().frame()->inputMethodController().compositionNode() == renderer().node();
617     bool useCustomUnderlines = containsComposition && renderer().frame()->inputMethodController().compositionUsesCustomUnderlines();
618
619     // Determine text colors.
620     TextPaintingStyle textStyle = textPaintingStyle(renderer(), styleToUse, paintInfo.forceBlackText(), isPrinting);
621     TextPaintingStyle selectionStyle = selectionPaintingStyle(renderer(), haveSelection, paintInfo.forceBlackText(), isPrinting, textStyle);
622     bool paintSelectedTextOnly = (paintInfo.phase == PaintPhaseSelection);
623     bool paintSelectedTextSeparately = !paintSelectedTextOnly && textStyle != selectionStyle;
624
625     // Set our font.
626     const Font& font = styleToUse->font();
627
628     FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
629     if (combinedText)
630         combinedText->adjustTextOrigin(textOrigin, boxRect);
631
632     // 1. Paint backgrounds behind text if needed. Examples of such backgrounds include selection
633     // and composition highlights.
634     if (paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseTextClip && !isPrinting) {
635         if (containsComposition) {
636             paintCompositionBackgrounds(context, boxOrigin, styleToUse, font, useCustomUnderlines);
637         }
638
639         paintDocumentMarkers(context, boxOrigin, styleToUse, font, true);
640
641         if (haveSelection && !useCustomUnderlines)
642             paintSelection(context, boxOrigin, styleToUse, font, selectionStyle.fillColor);
643     }
644
645     // 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
646     int length = m_len;
647     int maximumLength;
648     StringView string;
649     if (!combinedText) {
650         string = renderer().text().createView();
651         if (static_cast<unsigned>(length) != string.length() || m_start)
652             string.narrow(m_start, length);
653         maximumLength = renderer().textLength() - m_start;
654     } else {
655         combinedText->getStringToRender(m_start, string, length);
656         maximumLength = length;
657     }
658
659     StringBuilder charactersWithHyphen;
660     TextRun textRun = constructTextRun(styleToUse, font, string, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
661     if (hasHyphen())
662         length = textRun.length();
663
664     int sPos = 0;
665     int ePos = 0;
666     if (paintSelectedTextOnly || paintSelectedTextSeparately)
667         selectionStartEnd(sPos, ePos);
668
669     if (m_truncation != cNoTruncation) {
670         sPos = std::min<int>(sPos, m_truncation);
671         ePos = std::min<int>(ePos, m_truncation);
672         length = m_truncation;
673     }
674
675     int emphasisMarkOffset = 0;
676     TextEmphasisPosition emphasisMarkPosition;
677     bool hasTextEmphasis = getEmphasisMarkPosition(styleToUse, emphasisMarkPosition);
678     const AtomicString& emphasisMark = hasTextEmphasis ? styleToUse->textEmphasisMarkString() : nullAtom;
679     if (!emphasisMark.isEmpty())
680         emphasisMarkOffset = emphasisMarkPosition == TextEmphasisPositionOver ? -font.fontMetrics().ascent() - font.emphasisMarkDescent(emphasisMark) : font.fontMetrics().descent() + font.emphasisMarkAscent(emphasisMark);
681
682     if (!paintSelectedTextOnly) {
683         // FIXME: Truncate right-to-left text correctly.
684         int startOffset = 0;
685         int endOffset = length;
686         if (paintSelectedTextSeparately && ePos > sPos) {
687             startOffset = ePos;
688             endOffset = sPos;
689         }
690
691         // For stroked painting, we have to change the text drawing mode.  It's probably dangerous to leave that mutated as a side
692         // effect, so only when we know we're stroking, do a save/restore.
693         GraphicsContextStateSaver stateSaver(*context, textStyle.strokeWidth > 0);
694
695         updateGraphicsContext(context, textStyle.fillColor, textStyle.strokeColor, textStyle.strokeWidth);
696         paintTextWithShadows(context, font, textRun, nullAtom, 0, startOffset, endOffset, length, textOrigin, boxRect, textStyle.shadow, isHorizontal());
697
698         if (!emphasisMark.isEmpty())
699             paintEmphasisMark(context, emphasisMark, emphasisMarkOffset, startOffset, endOffset, length, font, textStyle.emphasisMarkColor, textStyle.strokeColor, textStyle.strokeWidth, textStyle.shadow, combinedText, textRun, textOrigin, boxRect, isHorizontal());
700     }
701
702     if ((paintSelectedTextOnly || paintSelectedTextSeparately) && sPos < ePos) {
703         // paint only the text that is selected
704         GraphicsContextStateSaver stateSaver(*context, selectionStyle.strokeWidth > 0);
705
706         updateGraphicsContext(context, selectionStyle.fillColor, selectionStyle.strokeColor, selectionStyle.strokeWidth);
707         paintTextWithShadows(context, font, textRun, nullAtom, 0, sPos, ePos, length, textOrigin, boxRect, selectionStyle.shadow, isHorizontal());
708
709         if (!emphasisMark.isEmpty())
710             paintEmphasisMark(context, emphasisMark, emphasisMarkOffset, sPos, ePos, length, font, selectionStyle.emphasisMarkColor, selectionStyle.strokeColor, textStyle.strokeWidth, selectionStyle.shadow, combinedText, textRun, textOrigin, boxRect, isHorizontal());
711     }
712
713     // Paint decorations
714     TextDecoration textDecorations = styleToUse->textDecorationsInEffect();
715     if (textDecorations != TextDecorationNone && paintInfo.phase != PaintPhaseSelection) {
716         updateGraphicsContext(context, textStyle.fillColor, textStyle.strokeColor, textStyle.strokeWidth);
717         if (combinedText)
718             context->concatCTM(rotation(boxRect, Clockwise));
719         paintDecoration(context, boxOrigin, textDecorations, textStyle.shadow);
720         if (combinedText)
721             context->concatCTM(rotation(boxRect, Counterclockwise));
722     }
723
724     if (paintInfo.phase == PaintPhaseForeground) {
725         paintDocumentMarkers(context, boxOrigin, styleToUse, font, false);
726
727         // Paint custom underlines for compositions.
728         if (useCustomUnderlines) {
729             const Vector<CompositionUnderline>& underlines = renderer().frame()->inputMethodController().customCompositionUnderlines();
730             CompositionUnderlineRangeFilter filter(underlines, start(), end());
731             for (CompositionUnderlineRangeFilter::ConstIterator it = filter.begin(); it != filter.end(); ++it) {
732                 if (it->color == Color::transparent)
733                     continue;
734                 paintCompositionUnderline(context, boxOrigin, *it);
735             }
736         }
737     }
738
739     if (shouldRotate)
740         context->concatCTM(rotation(boxRect, Counterclockwise));
741 }
742
743 void InlineTextBox::selectionStartEnd(int& sPos, int& ePos)
744 {
745     int startPos, endPos;
746     if (renderer().selectionState() == RenderObject::SelectionInside) {
747         startPos = 0;
748         endPos = renderer().textLength();
749     } else {
750         renderer().selectionStartEnd(startPos, endPos);
751         if (renderer().selectionState() == RenderObject::SelectionStart)
752             endPos = renderer().textLength();
753         else if (renderer().selectionState() == RenderObject::SelectionEnd)
754             startPos = 0;
755     }
756
757     sPos = std::max(startPos - m_start, 0);
758     ePos = std::min(endPos - m_start, (int)m_len);
759 }
760
761 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color textColor)
762 {
763     // See if we have a selection to paint at all.
764     int sPos, ePos;
765     selectionStartEnd(sPos, ePos);
766     if (sPos >= ePos)
767         return;
768
769     Color c = renderer().selectionBackgroundColor();
770     if (!c.alpha())
771         return;
772
773     // If the text color ends up being the same as the selection background, invert the selection
774     // background.
775     if (textColor == c)
776         c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
777
778     GraphicsContextStateSaver stateSaver(*context);
779     updateGraphicsContext(context, c, c, 0); // Don't draw text at all!
780
781     // If the text is truncated, let the thing being painted in the truncation
782     // draw its own highlight.
783     int length = m_truncation != cNoTruncation ? m_truncation : m_len;
784     StringView string = renderer().text().createView();
785
786     if (string.length() != static_cast<unsigned>(length) || m_start)
787         string.narrow(m_start, length);
788
789     StringBuilder charactersWithHyphen;
790     bool respectHyphen = ePos == length && hasHyphen();
791     TextRun textRun = constructTextRun(style, font, string, renderer().textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
792     if (respectHyphen)
793         ePos = textRun.length();
794
795     LayoutUnit selectionBottom = root().selectionBottom();
796     LayoutUnit selectionTop = root().selectionTopAdjustedForPrecedingBlock();
797
798     int deltaY = roundToInt(renderer().style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
799     int selHeight = std::max(0, roundToInt(selectionBottom - selectionTop));
800
801     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
802     FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
803     context->clip(clipRect);
804
805     context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, sPos, ePos);
806 }
807
808 unsigned InlineTextBox::underlinePaintStart(const CompositionUnderline& underline)
809 {
810     return std::max(static_cast<unsigned>(m_start), underline.startOffset);
811 }
812
813 unsigned InlineTextBox::underlinePaintEnd(const CompositionUnderline& underline)
814 {
815     unsigned paintEnd = std::min(end() + 1, underline.endOffset); // end() points at the last char, not past it.
816     if (m_truncation != cNoTruncation)
817         paintEnd = std::min(paintEnd, static_cast<unsigned>(m_start + m_truncation));
818     return paintEnd;
819 }
820
821 void InlineTextBox::paintSingleCompositionBackgroundRun(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color backgroundColor, int startPos, int endPos)
822 {
823     int sPos = std::max(startPos - m_start, 0);
824     int ePos = std::min(endPos - m_start, static_cast<int>(m_len));
825     if (sPos >= ePos)
826         return;
827
828     GraphicsContextStateSaver stateSaver(*context);
829
830     updateGraphicsContext(context, backgroundColor, backgroundColor, 0); // Don't draw text at all!
831
832     int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
833     int selHeight = selectionHeight();
834     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
835     context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, backgroundColor, sPos, ePos);
836 }
837
838 static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorationStyle)
839 {
840     StrokeStyle strokeStyle = SolidStroke;
841     switch (decorationStyle) {
842     case TextDecorationStyleSolid:
843         strokeStyle = SolidStroke;
844         break;
845     case TextDecorationStyleDouble:
846         strokeStyle = DoubleStroke;
847         break;
848     case TextDecorationStyleDotted:
849         strokeStyle = DottedStroke;
850         break;
851     case TextDecorationStyleDashed:
852         strokeStyle = DashedStroke;
853         break;
854     case TextDecorationStyleWavy:
855         strokeStyle = WavyStroke;
856         break;
857     }
858
859     return strokeStyle;
860 }
861
862 static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const float textDecorationThickness)
863 {
864     // Compute the gap between the font and the underline. Use at least one
865     // pixel gap, if underline is thick then use a bigger gap.
866     int gap = 0;
867
868     // Underline position of zero means draw underline on Baseline Position,
869     // in Blink we need at least 1-pixel gap to adding following check.
870     // Positive underline Position means underline should be drawn above baselin e
871     // and negative value means drawing below baseline, negating the value as in Blink
872     // downward Y-increases.
873
874     if (fontMetrics.underlinePosition())
875         gap = -fontMetrics.underlinePosition();
876     else
877         gap = std::max<int>(1, ceilf(textDecorationThickness / 2.f));
878
879     // FIXME: We support only horizontal text for now.
880     switch (underlinePosition) {
881     case TextUnderlinePositionAuto:
882         return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
883     case TextUnderlinePositionUnder: {
884         // Position underline relative to the under edge of the lowest element's content box.
885         const float offset = inlineTextBox->root().maxLogicalTop() - inlineTextBox->logicalTop();
886         if (offset > 0)
887             return inlineTextBox->logicalHeight() + gap + offset;
888         return inlineTextBox->logicalHeight() + gap;
889     }
890     }
891
892     ASSERT_NOT_REACHED();
893     return fontMetrics.ascent() + gap;
894 }
895
896 static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
897 {
898     ASSERT(step > 0);
899
900     if (length <= 0)
901         return;
902
903     unsigned stepCount = static_cast<unsigned>(length / step);
904
905     // Each Bezier curve starts at the same pixel that the previous one
906     // ended. We need to subtract (stepCount - 1) pixels when calculating the
907     // length covered to account for that.
908     float uncoveredLength = length - (stepCount * step - (stepCount - 1));
909     float adjustment = uncoveredLength / stepCount;
910     step += adjustment;
911     controlPointDistance += adjustment;
912 }
913
914 /*
915  * Draw one cubic Bezier curve and repeat the same pattern long the the decoration's axis.
916  * The start point (p1), controlPoint1, controlPoint2 and end point (p2) of the Bezier curve
917  * form a diamond shape:
918  *
919  *                              step
920  *                         |-----------|
921  *
922  *                   controlPoint1
923  *                         +
924  *
925  *
926  *                  . .
927  *                .     .
928  *              .         .
929  * (x1, y1) p1 +           .            + p2 (x2, y2) - <--- Decoration's axis
930  *                          .         .               |
931  *                            .     .                 |
932  *                              . .                   | controlPointDistance
933  *                                                    |
934  *                                                    |
935  *                         +                          -
936  *                   controlPoint2
937  *
938  *             |-----------|
939  *                 step
940  */
941 static void strokeWavyTextDecoration(GraphicsContext* context, FloatPoint p1, FloatPoint p2, float strokeThickness)
942 {
943     context->adjustLineToPixelBoundaries(p1, p2, strokeThickness, context->strokeStyle());
944
945     Path path;
946     path.moveTo(p1);
947
948     // Distance between decoration's axis and Bezier curve's control points.
949     // The height of the curve is based on this distance. Use a minimum of 6 pixels distance since
950     // the actual curve passes approximately at half of that distance, that is 3 pixels.
951     // The minimum height of the curve is also approximately 3 pixels. Increases the curve's height
952     // as strockThickness increases to make the curve looks better.
953     float controlPointDistance = 3 * std::max<float>(2, strokeThickness);
954
955     // Increment used to form the diamond shape between start point (p1), control
956     // points and end point (p2) along the axis of the decoration. Makes the
957     // curve wider as strockThickness increases to make the curve looks better.
958     float step = 2 * std::max<float>(2, strokeThickness);
959
960     bool isVerticalLine = (p1.x() == p2.x());
961
962     if (isVerticalLine) {
963         ASSERT(p1.x() == p2.x());
964
965         float xAxis = p1.x();
966         float y1;
967         float y2;
968
969         if (p1.y() < p2.y()) {
970             y1 = p1.y();
971             y2 = p2.y();
972         } else {
973             y1 = p2.y();
974             y2 = p1.y();
975         }
976
977         adjustStepToDecorationLength(step, controlPointDistance, y2 - y1);
978         FloatPoint controlPoint1(xAxis + controlPointDistance, 0);
979         FloatPoint controlPoint2(xAxis - controlPointDistance, 0);
980
981         for (float y = y1; y + 2 * step <= y2;) {
982             controlPoint1.setY(y + step);
983             controlPoint2.setY(y + step);
984             y += 2 * step;
985             path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(xAxis, y));
986         }
987     } else {
988         ASSERT(p1.y() == p2.y());
989
990         float yAxis = p1.y();
991         float x1;
992         float x2;
993
994         if (p1.x() < p2.x()) {
995             x1 = p1.x();
996             x2 = p2.x();
997         } else {
998             x1 = p2.x();
999             x2 = p1.x();
1000         }
1001
1002         adjustStepToDecorationLength(step, controlPointDistance, x2 - x1);
1003         FloatPoint controlPoint1(0, yAxis + controlPointDistance);
1004         FloatPoint controlPoint2(0, yAxis - controlPointDistance);
1005
1006         for (float x = x1; x + 2 * step <= x2;) {
1007             controlPoint1.setX(x + step);
1008             controlPoint2.setX(x + step);
1009             x += 2 * step;
1010             path.addBezierCurveTo(controlPoint1, controlPoint2, FloatPoint(x, yAxis));
1011         }
1012     }
1013
1014     context->setShouldAntialias(true);
1015     context->strokePath(path);
1016 }
1017
1018 static bool shouldSetDecorationAntialias(TextDecorationStyle decorationStyle)
1019 {
1020     return decorationStyle == TextDecorationStyleDotted || decorationStyle == TextDecorationStyleDashed;
1021 }
1022
1023 static bool shouldSetDecorationAntialias(TextDecorationStyle underline, TextDecorationStyle overline, TextDecorationStyle linethrough)
1024 {
1025     return shouldSetDecorationAntialias(underline) || shouldSetDecorationAntialias(overline) || shouldSetDecorationAntialias(linethrough);
1026 }
1027
1028 static void paintAppliedDecoration(GraphicsContext* context, FloatPoint start, float width, float doubleOffset, int wavyOffsetFactor,
1029     RenderObject::AppliedTextDecoration decoration, float thickness, bool antialiasDecoration, bool isPrinting)
1030 {
1031     context->setStrokeStyle(textDecorationStyleToStrokeStyle(decoration.style));
1032     context->setStrokeColor(decoration.color);
1033
1034     switch (decoration.style) {
1035     case TextDecorationStyleWavy:
1036         strokeWavyTextDecoration(context, start + FloatPoint(0, doubleOffset * wavyOffsetFactor), start + FloatPoint(width, doubleOffset * wavyOffsetFactor), thickness);
1037         break;
1038     case TextDecorationStyleDotted:
1039     case TextDecorationStyleDashed:
1040         context->setShouldAntialias(antialiasDecoration);
1041         // Fall through
1042     default:
1043         context->drawLineForText(start, width, isPrinting);
1044
1045         if (decoration.style == TextDecorationStyleDouble)
1046             context->drawLineForText(start + FloatPoint(0, doubleOffset), width, isPrinting);
1047     }
1048 }
1049
1050 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, const ShadowList* shadowList)
1051 {
1052     GraphicsContextStateSaver stateSaver(*context);
1053
1054     if (m_truncation == cFullTruncation)
1055         return;
1056
1057     FloatPoint localOrigin = boxOrigin;
1058
1059     float width = m_logicalWidth;
1060     if (m_truncation != cNoTruncation) {
1061         width = renderer().width(m_start, m_truncation, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1062         if (!isLeftToRightDirection())
1063             localOrigin.move(m_logicalWidth - width, 0);
1064     }
1065
1066     // Get the text decoration colors.
1067     RenderObject::AppliedTextDecoration underline, overline, linethrough;
1068
1069     renderer().getTextDecorations(deco, underline, overline, linethrough, true);
1070     if (isFirstLineStyle())
1071         renderer().getTextDecorations(deco, underline, overline, linethrough, true, true);
1072
1073     // Use a special function for underlines to get the positioning exactly right.
1074     bool isPrinting = renderer().document().printing();
1075
1076     bool linesAreOpaque = !isPrinting && (!(deco & TextDecorationUnderline) || underline.color.alpha() == 255) && (!(deco & TextDecorationOverline) || overline.color.alpha() == 255) && (!(deco & TextDecorationLineThrough) || linethrough.color.alpha() == 255);
1077
1078     RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
1079     int baseline = styleToUse->fontMetrics().ascent();
1080
1081     size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
1082     // Set the thick of the line to be 10% (or something else ?)of the computed font size and not less than 1px.
1083     // Using computedFontSize should take care of zoom as well.
1084
1085     // Update Underline thickness, in case we have Faulty Font Metrics calculating underline thickness by old method.
1086     float textDecorationThickness = styleToUse->fontMetrics().underlineThickness();
1087     int fontHeightInt  = (int)(styleToUse->fontMetrics().floatHeight() + 0.5);
1088     if ((textDecorationThickness == 0.f) || (textDecorationThickness >= (fontHeightInt >> 1)))
1089         textDecorationThickness = std::max(1.f, styleToUse->computedFontSize() / 10.f);
1090
1091     context->setStrokeThickness(textDecorationThickness);
1092
1093     bool antialiasDecoration = shouldSetDecorationAntialias(overline.style, underline.style, linethrough.style)
1094         && RenderBoxModelObject::shouldAntialiasLines(context);
1095
1096     float extraOffset = 0;
1097     if (!linesAreOpaque && shadowCount > 1) {
1098         FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1099         for (size_t i = shadowCount; i--; ) {
1100             const ShadowData& s = shadowList->shadows()[i];
1101             FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1102             shadowRect.inflate(s.blur());
1103             float shadowX = isHorizontal() ? s.x() : s.y();
1104             float shadowY = isHorizontal() ? s.y() : -s.x();
1105             shadowRect.move(shadowX, shadowY);
1106             clipRect.unite(shadowRect);
1107             extraOffset = std::max(extraOffset, std::max(0.0f, shadowY) + s.blur());
1108         }
1109         context->clip(clipRect);
1110         extraOffset += baseline + 2;
1111         localOrigin.move(0, extraOffset);
1112     }
1113
1114     for (size_t i = std::max(static_cast<size_t>(1), shadowCount); i--; ) {
1115         // Even if we have no shadows, we still want to run the code below this once.
1116         if (i < shadowCount) {
1117             if (!i) {
1118                 // The last set of lines paints normally inside the clip.
1119                 localOrigin.move(0, -extraOffset);
1120                 extraOffset = 0;
1121             }
1122             const ShadowData& shadow = shadowList->shadows()[i];
1123             float shadowX = isHorizontal() ? shadow.x() : shadow.y();
1124             float shadowY = isHorizontal() ? shadow.y() : -shadow.x();
1125             context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow.blur(), shadow.color());
1126         }
1127
1128         // Offset between lines - always non-zero, so lines never cross each other.
1129         float doubleOffset = textDecorationThickness + 1.f;
1130
1131         if (deco & TextDecorationUnderline) {
1132             const int underlineOffset = computeUnderlineOffset(styleToUse->textUnderlinePosition(), styleToUse->fontMetrics(), this, textDecorationThickness);
1133             paintAppliedDecoration(context, localOrigin + FloatPoint(0, underlineOffset), width, doubleOffset, 1, underline, textDecorationThickness, antialiasDecoration, isPrinting);
1134         }
1135         if (deco & TextDecorationOverline) {
1136             paintAppliedDecoration(context, localOrigin, width, -doubleOffset, 1, overline, textDecorationThickness, antialiasDecoration, isPrinting);
1137         }
1138         if (deco & TextDecorationLineThrough) {
1139             const float lineThroughOffset = 2 * baseline / 3;
1140             paintAppliedDecoration(context, localOrigin + FloatPoint(0, lineThroughOffset), width, doubleOffset, 0, linethrough, textDecorationThickness, antialiasDecoration, isPrinting);
1141         }
1142     }
1143 }
1144
1145 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1146 {
1147     switch (markerType) {
1148     case DocumentMarker::Spelling:
1149         return GraphicsContext::DocumentMarkerSpellingLineStyle;
1150     case DocumentMarker::Grammar:
1151         return GraphicsContext::DocumentMarkerGrammarLineStyle;
1152     default:
1153         ASSERT_NOT_REACHED();
1154         return GraphicsContext::DocumentMarkerSpellingLineStyle;
1155     }
1156 }
1157
1158 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1159 {
1160     // Never print spelling/grammar markers (5327887)
1161     if (renderer().document().printing())
1162         return;
1163
1164     if (m_truncation == cFullTruncation)
1165         return;
1166
1167     float start = 0; // start of line to draw, relative to tx
1168     float width = m_logicalWidth; // how much line to draw
1169
1170     // Determine whether we need to measure text
1171     bool markerSpansWholeBox = true;
1172     if (m_start <= (int)marker->startOffset())
1173         markerSpansWholeBox = false;
1174     if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1175         markerSpansWholeBox = false;
1176     if (m_truncation != cNoTruncation)
1177         markerSpansWholeBox = false;
1178
1179     if (!markerSpansWholeBox || grammar) {
1180         int startPosition = std::max<int>(marker->startOffset() - m_start, 0);
1181         int endPosition = std::min<int>(marker->endOffset() - m_start, m_len);
1182
1183         if (m_truncation != cNoTruncation)
1184             endPosition = std::min<int>(endPosition, m_truncation);
1185
1186         // Calculate start & width
1187         int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1188         int selHeight = selectionHeight();
1189         FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1190         TextRun run = constructTextRun(style, font);
1191
1192         // FIXME: Convert the document markers to float rects.
1193         IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1194         start = markerRect.x() - startPoint.x();
1195         width = markerRect.width();
1196
1197         // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1198         // display a toolTip. We don't do this for misspelling markers.
1199         if (grammar) {
1200             markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1201             markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1202             toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1203         }
1204     }
1205
1206     // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1207     // make sure to fit within those bounds.  This means the top pixel(s) of the underline will overlap the
1208     // bottom pixel(s) of the glyphs in smaller font sizes.  The alternatives are to increase the line spacing (bad!!)
1209     // or decrease the underline thickness.  The overlap is actually the most useful, and matches what AppKit does.
1210     // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1211     // we pin to two pixels under the baseline.
1212     int lineThickness = misspellingLineThickness;
1213     int baseline = renderer().style(isFirstLineStyle())->fontMetrics().ascent();
1214     int descent = logicalHeight() - baseline;
1215     int underlineOffset;
1216     if (descent <= (2 + lineThickness)) {
1217         // Place the underline at the very bottom of the text in small/medium fonts.
1218         underlineOffset = logicalHeight() - lineThickness;
1219     } else {
1220         // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1221         underlineOffset = baseline + 2;
1222     }
1223     pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1224 }
1225
1226 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1227 {
1228     // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1229     // the same word there are no pieces sticking out.
1230     int deltaY = renderer().style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1231     int selHeight = selectionHeight();
1232
1233     int sPos = std::max(marker->startOffset() - m_start, (unsigned)0);
1234     int ePos = std::min(marker->endOffset() - m_start, (unsigned)m_len);
1235     TextRun run = constructTextRun(style, font);
1236
1237     // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1238     IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1239     markerRect = renderer().localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1240     toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1241
1242     // Optionally highlight the text
1243     if (renderer().frame()->editor().markedTextMatchesAreHighlighted()) {
1244         Color color = marker->activeMatch() ?
1245             RenderTheme::theme().platformActiveTextSearchHighlightColor() :
1246             RenderTheme::theme().platformInactiveTextSearchHighlightColor();
1247         GraphicsContextStateSaver stateSaver(*pt);
1248         updateGraphicsContext(pt, color, color, 0); // Don't draw text at all!
1249         pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1250         pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, sPos, ePos);
1251     }
1252 }
1253
1254 void InlineTextBox::paintCompositionBackgrounds(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool useCustomUnderlines)
1255 {
1256     if (useCustomUnderlines) {
1257         // Paint custom background highlights for compositions.
1258         const Vector<CompositionUnderline>& underlines = renderer().frame()->inputMethodController().customCompositionUnderlines();
1259         CompositionUnderlineRangeFilter filter(underlines, start(), end());
1260         for (CompositionUnderlineRangeFilter::ConstIterator it = filter.begin(); it != filter.end(); ++it) {
1261             if (it->backgroundColor == Color::transparent)
1262                 continue;
1263             paintSingleCompositionBackgroundRun(pt, boxOrigin, style, font, it->backgroundColor, underlinePaintStart(*it), underlinePaintEnd(*it));
1264         }
1265
1266     } else {
1267         paintSingleCompositionBackgroundRun(pt, boxOrigin, style, font, RenderTheme::theme().platformDefaultCompositionBackgroundColor(),
1268             renderer().frame()->inputMethodController().compositionStart(),
1269             renderer().frame()->inputMethodController().compositionEnd());
1270     }
1271 }
1272
1273 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1274 {
1275     if (!renderer().node())
1276         return;
1277
1278     DocumentMarkerVector markers = renderer().document().markers().markersFor(renderer().node());
1279     DocumentMarkerVector::const_iterator markerIt = markers.begin();
1280
1281     // Give any document markers that touch this run a chance to draw before the text has been drawn.
1282     // Note end() points at the last char, not one past it like endOffset and ranges do.
1283     for ( ; markerIt != markers.end(); ++markerIt) {
1284         DocumentMarker* marker = *markerIt;
1285
1286         // Paint either the background markers or the foreground markers, but not both
1287         switch (marker->type()) {
1288             case DocumentMarker::Grammar:
1289             case DocumentMarker::Spelling:
1290                 if (background)
1291                     continue;
1292                 break;
1293             case DocumentMarker::TextMatch:
1294                 if (!background)
1295                     continue;
1296                 break;
1297             default:
1298                 continue;
1299         }
1300
1301         if (marker->endOffset() <= start())
1302             // marker is completely before this run.  This might be a marker that sits before the
1303             // first run we draw, or markers that were within runs we skipped due to truncation.
1304             continue;
1305
1306         if (marker->startOffset() > end())
1307             // marker is completely after this run, bail.  A later run will paint it.
1308             break;
1309
1310         // marker intersects this run.  Paint it.
1311         switch (marker->type()) {
1312             case DocumentMarker::Spelling:
1313                 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1314                 break;
1315             case DocumentMarker::Grammar:
1316                 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1317                 break;
1318             case DocumentMarker::TextMatch:
1319                 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1320                 break;
1321             default:
1322                 ASSERT_NOT_REACHED();
1323         }
1324
1325     }
1326 }
1327
1328 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1329 {
1330     if (m_truncation == cFullTruncation)
1331         return;
1332
1333     unsigned paintStart = underlinePaintStart(underline);
1334     unsigned paintEnd = underlinePaintEnd(underline);
1335
1336     // start of line to draw, relative to paintOffset.
1337     float start = paintStart == static_cast<unsigned>(m_start) ? 0 :
1338         renderer().width(m_start, paintStart - m_start, textPos(), isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1339     // how much line to draw
1340     float width = (paintStart == static_cast<unsigned>(m_start) && paintEnd == static_cast<unsigned>(end()) + 1) ? m_logicalWidth :
1341         renderer().width(paintStart, paintEnd - paintStart, textPos() + start, isLeftToRightDirection() ? LTR : RTL, isFirstLineStyle());
1342
1343     // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1344     // All other marked text underlines are 1px thick.
1345     // If there's not enough space the underline will touch or overlap characters.
1346     int lineThickness = 1;
1347     int baseline = renderer().style(isFirstLineStyle())->fontMetrics().ascent();
1348     if (underline.thick && logicalHeight() - baseline >= 2)
1349         lineThickness = 2;
1350
1351     // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1352     // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1353     start += 1;
1354     width -= 2;
1355
1356     ctx->setStrokeColor(underline.color);
1357     ctx->setStrokeThickness(lineThickness);
1358     ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, renderer().document().printing());
1359 }
1360
1361 int InlineTextBox::caretMinOffset() const
1362 {
1363     return m_start;
1364 }
1365
1366 int InlineTextBox::caretMaxOffset() const
1367 {
1368     return m_start + m_len;
1369 }
1370
1371 float InlineTextBox::textPos() const
1372 {
1373     // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1374     // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1375     if (logicalLeft() == 0)
1376         return 0;
1377     return logicalLeft() - root().logicalLeft();
1378 }
1379
1380 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1381 {
1382     if (isLineBreak())
1383         return 0;
1384
1385     if (lineOffset - logicalLeft() > logicalWidth())
1386         return isLeftToRightDirection() ? len() : 0;
1387     if (lineOffset - logicalLeft() < 0)
1388         return isLeftToRightDirection() ? 0 : len();
1389
1390     FontCachePurgePreventer fontCachePurgePreventer;
1391
1392     RenderText& text = renderer();
1393     RenderStyle* style = text.style(isFirstLineStyle());
1394     const Font& font = style->font();
1395     return font.offsetForPosition(constructTextRun(style, font), lineOffset - logicalLeft(), includePartialGlyphs);
1396 }
1397
1398 float InlineTextBox::positionForOffset(int offset) const
1399 {
1400     ASSERT(offset >= m_start);
1401     ASSERT(offset <= m_start + m_len);
1402
1403     if (isLineBreak())
1404         return logicalLeft();
1405
1406     FontCachePurgePreventer fontCachePurgePreventer;
1407
1408     RenderText& text = renderer();
1409     RenderStyle* styleToUse = text.style(isFirstLineStyle());
1410     ASSERT(styleToUse);
1411     const Font& font = styleToUse->font();
1412     int from = !isLeftToRightDirection() ? offset - m_start : 0;
1413     int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1414     // FIXME: Do we need to add rightBearing here?
1415     return font.selectionRectForText(constructTextRun(styleToUse, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1416 }
1417
1418 bool InlineTextBox::containsCaretOffset(int offset) const
1419 {
1420     // Offsets before the box are never "in".
1421     if (offset < m_start)
1422         return false;
1423
1424     int pastEnd = m_start + m_len;
1425
1426     // Offsets inside the box (not at either edge) are always "in".
1427     if (offset < pastEnd)
1428         return true;
1429
1430     // Offsets outside the box are always "out".
1431     if (offset > pastEnd)
1432         return false;
1433
1434     // Offsets at the end are "out" for line breaks (they are on the next line).
1435     if (isLineBreak())
1436         return false;
1437
1438     // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1439     return true;
1440 }
1441
1442 void InlineTextBox::characterWidths(Vector<float>& widths) const
1443 {
1444     FontCachePurgePreventer fontCachePurgePreventer;
1445
1446     RenderStyle* styleToUse = renderer().style(isFirstLineStyle());
1447     const Font& font = styleToUse->font();
1448
1449     TextRun textRun = constructTextRun(styleToUse, font);
1450
1451     GlyphBuffer glyphBuffer;
1452     WidthIterator it(&font, textRun);
1453     float lastWidth = 0;
1454     widths.resize(m_len);
1455     for (unsigned i = 0; i < m_len; i++) {
1456         it.advance(i + 1, &glyphBuffer);
1457         widths[i] = it.m_runWidthSoFar - lastWidth;
1458         lastWidth = it.m_runWidthSoFar;
1459     }
1460 }
1461
1462 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringBuilder* charactersWithHyphen) const
1463 {
1464     ASSERT(style);
1465     ASSERT(renderer().text());
1466
1467     StringView string = renderer().text().createView();
1468     unsigned startPos = start();
1469     unsigned length = len();
1470
1471     if (string.length() != length || startPos)
1472         string.narrow(startPos, length);
1473
1474     return constructTextRun(style, font, string, renderer().textLength() - startPos, charactersWithHyphen);
1475 }
1476
1477 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringView string, int maximumLength, StringBuilder* charactersWithHyphen) const
1478 {
1479     ASSERT(style);
1480
1481     if (charactersWithHyphen) {
1482         const AtomicString& hyphenString = style->hyphenString();
1483         charactersWithHyphen->reserveCapacity(string.length() + hyphenString.length());
1484         charactersWithHyphen->append(string);
1485         charactersWithHyphen->append(hyphenString);
1486         string = charactersWithHyphen->toString().createView();
1487         maximumLength = string.length();
1488     }
1489
1490     ASSERT(maximumLength >= static_cast<int>(string.length()));
1491
1492     TextRun run(string, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !renderer().canUseSimpleFontCodePath());
1493     run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
1494     run.setCharacterScanForCodePath(!renderer().canUseSimpleFontCodePath());
1495     if (textRunNeedsRenderingContext(font))
1496         run.setRenderingContext(SVGTextRunRenderingContext::create(&renderer()));
1497
1498     // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1499     run.setCharactersLength(maximumLength);
1500     ASSERT(run.charactersLength() >= run.length());
1501     return run;
1502 }
1503
1504 TextRun InlineTextBox::constructTextRunForInspector(RenderStyle* style, const Font& font) const
1505 {
1506     return InlineTextBox::constructTextRun(style, font);
1507 }
1508
1509 #ifndef NDEBUG
1510
1511 const char* InlineTextBox::boxName() const
1512 {
1513     return "InlineTextBox";
1514 }
1515
1516 void InlineTextBox::showBox(int printedCharacters) const
1517 {
1518     const RenderText& obj = renderer();
1519     String value = obj.text();
1520     value = value.substring(start(), len());
1521     value.replaceWithLiteral('\\', "\\\\");
1522     value.replaceWithLiteral('\n', "\\n");
1523     printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1524     for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1525         fputc(' ', stderr);
1526     printedCharacters = fprintf(stderr, "\t%s %p", obj.renderName(), &obj);
1527     const int rendererCharacterOffset = 24;
1528     for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1529         fputc(' ', stderr);
1530     fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1531 }
1532
1533 #endif
1534
1535 } // namespace blink