19a3b1b7e576c7e8b2e4fdad8a17261d4b6dd0e7
[framework/web/webkit-efl.git] / Source / WebCore / 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 "InlineTextBox.h"
25
26 #include "Chrome.h"
27 #include "ChromeClient.h"
28 #include "Document.h"
29 #include "DocumentMarkerController.h"
30 #include "Editor.h"
31 #include "EllipsisBox.h"
32 #include "FontCache.h"
33 #include "Frame.h"
34 #include "GraphicsContext.h"
35 #include "HitTestResult.h"
36 #include "Page.h"
37 #include "PaintInfo.h"
38 #include "RenderedDocumentMarker.h"
39 #include "RenderArena.h"
40 #include "RenderBR.h"
41 #include "RenderBlock.h"
42 #include "RenderCombineText.h"
43 #include "RenderRubyRun.h"
44 #include "RenderRubyText.h"
45 #include "RenderTheme.h"
46 #include "Settings.h"
47 #include "SVGTextRunRenderingContext.h"
48 #include "Text.h"
49 #include "break_lines.h"
50 #include <wtf/AlwaysInline.h>
51 #include <wtf/text/CString.h>
52
53 using namespace std;
54
55 namespace WebCore {
56
57 typedef WTF::HashMap<const InlineTextBox*, LayoutRect> InlineTextBoxOverflowMap;
58 static InlineTextBoxOverflowMap* gTextBoxesWithOverflow;
59
60 void InlineTextBox::destroy(RenderArena* arena)
61 {
62     if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
63         gTextBoxesWithOverflow->remove(this);
64     InlineBox::destroy(arena);
65 }
66
67 LayoutRect InlineTextBox::logicalOverflowRect() const
68 {
69     if (knownToHaveNoOverflow() || !gTextBoxesWithOverflow)
70         return enclosingIntRect(logicalFrameRect());
71     return gTextBoxesWithOverflow->get(this);
72 }
73
74 void InlineTextBox::setLogicalOverflowRect(const LayoutRect& rect)
75 {
76     ASSERT(!knownToHaveNoOverflow());
77     if (!gTextBoxesWithOverflow)
78         gTextBoxesWithOverflow = new InlineTextBoxOverflowMap;
79     gTextBoxesWithOverflow->add(this, rect);
80 }
81
82 LayoutUnit InlineTextBox::baselinePosition(FontBaseline baselineType) const
83 {
84     if (!isText() || !parent())
85         return 0;
86     if (parent()->renderer() == renderer()->parent())
87         return parent()->baselinePosition(baselineType);
88     return toRenderBoxModelObject(renderer()->parent())->baselinePosition(baselineType, isFirstLineStyle(), isHorizontal() ? HorizontalLine : VerticalLine, PositionOnContainingLine);
89 }
90
91 LayoutUnit InlineTextBox::lineHeight() const
92 {
93     if (!isText() || !renderer()->parent())
94         return 0;
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);
100 }
101
102 LayoutUnit InlineTextBox::selectionTop()
103 {
104     return root()->selectionTop();
105 }
106
107 LayoutUnit InlineTextBox::selectionBottom()
108 {
109     return root()->selectionBottom();
110 }
111
112 LayoutUnit InlineTextBox::selectionHeight()
113 {
114     return root()->selectionHeight();
115 }
116
117 bool InlineTextBox::isSelected(int startPos, int endPos) const
118 {
119     LayoutUnit sPos = max<LayoutUnit>(startPos - m_start, 0);
120     LayoutUnit ePos = min<LayoutUnit>(endPos - m_start, m_len);
121     return (sPos < ePos);
122 }
123
124 RenderObject::SelectionState InlineTextBox::selectionState()
125 {
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);
132
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);
135         if (start && end)
136             state = RenderObject::SelectionBoth;
137         else if (start)
138             state = RenderObject::SelectionStart;
139         else if (end)
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;
146     }
147
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) {
152             int start, end;
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
157             // truncation.
158             ellipsis->setSelectionState(end >= m_truncation && start <= m_truncation ?
159                 RenderObject::SelectionInside : RenderObject::SelectionNone);
160         } else
161             ellipsis->setSelectionState(RenderObject::SelectionNone);
162     }
163
164     return state;
165 }
166
167 static void adjustCharactersAndLengthForHyphen(BufferForAppendingHyphen& charactersWithHyphen, RenderStyle* style, const UChar*& characters, int& length)
168 {
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();
175 }
176
177 LayoutRect InlineTextBox::localSelectionRect(int startPos, int endPos)
178 {
179     int sPos = max(startPos - m_start, 0);
180     int ePos = min(endPos - m_start, (int)m_len);
181     
182     if (sPos > ePos)
183         return LayoutRect();
184
185     FontCachePurgePreventer fontCachePurgePreventer;
186
187     RenderText* textObj = textRenderer();
188     LayoutUnit selTop = selectionTop();
189     LayoutUnit selHeight = selectionHeight();
190     RenderStyle* styleToUse = textObj->style(isFirstLineStyle());
191     const Font& font = styleToUse->font();
192
193     BufferForAppendingHyphen charactersWithHyphen;
194     bool respectHyphen = ePos == m_len && hasHyphen();
195     TextRun textRun = constructTextRun(styleToUse, font, respectHyphen ? &charactersWithHyphen : 0);
196     if (respectHyphen)
197         endPos = textRun.length();
198
199     LayoutRect r = enclosingIntRect(font.selectionRectForText(textRun, FloatPoint(logicalLeft(), selTop), selHeight, sPos, ePos));
200
201     LayoutUnit logicalWidth = r.width();
202     if (r.x() > logicalRight())
203         logicalWidth  = 0;
204     else if (r.maxX() > logicalRight())
205         logicalWidth = logicalRight() - r.x();
206
207     LayoutPoint topPoint = isHorizontal() ? LayoutPoint(r.x(), selTop) : LayoutPoint(selTop, r.x());
208     LayoutUnit width = isHorizontal() ? logicalWidth : selHeight;
209     LayoutUnit height = isHorizontal() ? selHeight : logicalWidth;
210
211     return LayoutRect(topPoint, LayoutSize(width, height));
212 }
213
214 void InlineTextBox::deleteLine(RenderArena* arena)
215 {
216     toRenderText(renderer())->removeTextBox(this);
217     destroy(arena);
218 }
219
220 void InlineTextBox::extractLine()
221 {
222     if (extracted())
223         return;
224
225     toRenderText(renderer())->extractTextBox(this);
226 }
227
228 void InlineTextBox::attachLine()
229 {
230     if (!extracted())
231         return;
232     
233     toRenderText(renderer())->attachTextBox(this);
234 }
235
236 float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, float visibleRightEdge, float ellipsisWidth, float &truncatedWidth, bool& foundBox)
237 {
238     if (foundBox) {
239         m_truncation = cFullTruncation;
240         return -1;
241     }
242
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;
245     
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;
254         foundBox = true;
255         return -1;
256     }
257
258     bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < right());
259     bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > left());
260     if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
261         foundBox = true;
262
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;
271         }
272
273         int offset = offsetForPosition(ellipsisX, false);
274         if (offset == 0) {
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());
280         }
281
282         // Set the truncation index on the text run.
283         m_truncation = offset;
284
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());
288
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;
295         if (flowIsLTR)
296             return left() + widthOfVisibleText;
297         else
298             return right() - widthOfVisibleText - ellipsisWidth;
299     }
300     truncatedWidth += logicalWidth();
301     return -1;
302 }
303
304 Color correctedTextColor(Color textColor, Color backgroundColor) 
305 {
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.
308     
309     int d = differenceSquared(textColor, backgroundColor);
310     // semi-arbitrarily chose 65025 (255^2) value here after a few tests; 
311     if (d > 65025) {
312         return textColor;
313     }
314     
315     int distanceFromWhite = differenceSquared(textColor, Color::white);
316     int distanceFromBlack = differenceSquared(textColor, Color::black);
317
318     if (distanceFromWhite < distanceFromBlack) {
319         return textColor.dark();
320     }
321     
322     return textColor.light();
323 }
324
325 void updateGraphicsContext(GraphicsContext* context, const Color& fillColor, const Color& strokeColor, float strokeThickness, ColorSpace colorSpace)
326 {
327     TextDrawingModeFlags mode = context->textDrawingMode();
328     if (strokeThickness > 0) {
329         TextDrawingModeFlags newMode = mode | TextModeStroke;
330         if (mode != newMode) {
331             context->setTextDrawingMode(newMode);
332             mode = newMode;
333         }
334     }
335     
336     if (mode & TextModeFill && (fillColor != context->fillColor() || colorSpace != context->fillColorSpace()))
337         context->setFillColor(fillColor, colorSpace);
338
339     if (mode & TextModeStroke) {
340         if (strokeColor != context->strokeColor())
341             context->setStrokeColor(strokeColor, colorSpace);
342         if (strokeThickness != context->strokeThickness())
343             context->setStrokeThickness(strokeThickness);
344     }
345 }
346
347 bool InlineTextBox::isLineBreak() const
348 {
349     return renderer()->isBR() || (renderer()->style()->preserveNewline() && len() == 1 && (*textRenderer()->text())[start()] == '\n');
350 }
351
352 bool InlineTextBox::nodeAtPoint(const HitTestRequest&, HitTestResult& result, const HitTestPoint& pointInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit /* lineTop */, LayoutUnit /*lineBottom*/)
353 {
354     if (isLineBreak())
355         return false;
356
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))
363             return true;
364     }
365     return false;
366 }
367
368 FloatSize InlineTextBox::applyShadowToGraphicsContext(GraphicsContext* context, const ShadowData* shadow, const FloatRect& textRect, bool stroked, bool opaque, bool horizontal)
369 {
370     if (!shadow)
371         return FloatSize();
372
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();
379
380     if (shadow->next() || stroked || !opaque) {
381         FloatRect shadowRect(textRect);
382         shadowRect.inflate(shadowBlur);
383         shadowRect.move(shadowOffset);
384         context->save();
385         context->clip(shadowRect);
386
387         extraOffset = FloatSize(0, 2 * textRect.height() + max(0.0f, shadowOffset.height()) + shadowBlur);
388         shadowOffset -= extraOffset;
389     }
390
391     context->setShadow(shadowOffset, shadowBlur, shadowColor, context->fillColorSpace());
392     return extraOffset;
393 }
394
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)
397 {
398     Color fillColor = context->fillColor();
399     ColorSpace fillColorSpace = context->fillColorSpace();
400     bool opaque = fillColor.alpha() == 255;
401     if (!opaque)
402         context->setFillColor(Color::black, fillColorSpace);
403
404     do {
405         IntSize extraOffset;
406         if (shadow)
407             extraOffset = roundedIntSize(InlineTextBox::applyShadowToGraphicsContext(context, shadow, boxRect, stroked, opaque, horizontal));
408         else if (!opaque)
409             context->setFillColor(fillColor, fillColorSpace);
410
411         if (startOffset <= endOffset) {
412             if (emphasisMark.isEmpty())
413                 context->drawText(font, textRun, textOrigin + extraOffset, startOffset, endOffset);
414             else
415                 context->drawEmphasisMarks(font, textRun, emphasisMark, textOrigin + extraOffset + IntSize(0, emphasisMarkOffset), startOffset, endOffset);
416         } else {
417             if (endOffset > 0) {
418                 if (emphasisMark.isEmpty())
419                     context->drawText(font, textRun, textOrigin + extraOffset,  0, endOffset);
420                 else
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);
425                 else
426                     context->drawEmphasisMarks(font, textRun, emphasisMark, textOrigin + extraOffset + IntSize(0, emphasisMarkOffset),  startOffset, truncationPoint);
427             }
428         }
429
430         if (!shadow)
431             break;
432
433         if (shadow->next() || stroked || !opaque)
434             context->restore();
435         else
436             context->clearShadow();
437
438         shadow = shadow->next();
439     } while (shadow || stroked || !opaque);
440 }
441
442 bool InlineTextBox::getEmphasisMarkPosition(RenderStyle* style, TextEmphasisPosition& emphasisPosition) const
443 {
444     // This function returns true if there are text emphasis marks and they are suppressed by ruby text.
445     if (style->textEmphasisMark() == TextEmphasisMarkNone)
446         return false;
447
448     emphasisPosition = style->textEmphasisPosition();
449     if (emphasisPosition == TextEmphasisPositionUnder)
450         return true; // Ruby text is always over, so it cannot suppress emphasis marks under.
451
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.
455
456     if (!containingBlock->parent()->isRubyRun())
457         return true; // Cannot get the ruby text.
458
459     RenderRubyText* rubyText = toRenderRubyRun(containingBlock->parent())->rubyText();
460
461     // The emphasis marks over are suppressed only if there is a ruby text box and it not empty.
462     return !rubyText || !rubyText->firstLineBox();
463 }
464
465 enum RotationDirection { Counterclockwise, Clockwise };
466
467 static inline AffineTransform rotation(const FloatRect& boxRect, RotationDirection clockwise)
468 {
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());
471 }
472
473 void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
474 {
475     if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE ||
476         m_truncation == cFullTruncation || paintInfo.phase == PaintPhaseOutline || !m_len)
477         return;
478
479     ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);
480
481     LayoutUnit logicalLeftSide = logicalLeftVisualOverflow();
482     LayoutUnit logicalRightSide = logicalRightVisualOverflow();
483     LayoutUnit logicalStart = logicalLeftSide + (isHorizontal() ? paintOffset.x() : paintOffset.y());
484     LayoutUnit logicalExtent = logicalRightSide - logicalLeftSide;
485     
486     LayoutUnit paintEnd = isHorizontal() ? paintInfo.rect.maxX() : paintInfo.rect.maxY();
487     LayoutUnit paintStart = isHorizontal() ? paintInfo.rect.x() : paintInfo.rect.y();
488     
489     LayoutPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
490     
491     if (logicalStart >= paintEnd || logicalStart + logicalExtent <= paintStart)
492         return;
493
494     bool isPrinting = textRenderer()->document()->printing();
495     
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.
500         return;
501
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());
517         }
518     }
519
520     GraphicsContext* context = paintInfo.context;
521
522     RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
523     
524     adjustedPaintOffset.move(0, styleToUse->isHorizontalWritingMode() ? 0 : -logicalHeight());
525
526     FloatPoint boxOrigin = locationIncludingFlipping();
527     boxOrigin.move(adjustedPaintOffset.x(), adjustedPaintOffset.y());
528     FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
529
530     RenderCombineText* combinedText = styleToUse->hasTextCombine() && textRenderer()->isCombineText() && toRenderCombineText(textRenderer())->isCombined() ? toRenderCombineText(textRenderer()) : 0;
531
532     bool shouldRotate = !isHorizontal() && !combinedText;
533     if (shouldRotate)
534         context->concatCTM(rotation(boxRect, Clockwise));
535
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();
539
540     // Determine the text colors and selection colors.
541     Color textFillColor;
542     Color textStrokeColor;
543     Color emphasisMarkColor;
544     float textStrokeWidth = styleToUse->textStrokeWidth();
545     const ShadowData* textShadow = paintInfo.forceBlackText ? 0 : styleToUse->textShadow();
546
547     if (paintInfo.forceBlackText) {
548         textFillColor = Color::black;
549         textStrokeColor = Color::black;
550         emphasisMarkColor = Color::black;
551     } else {
552         textFillColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextFillColor);
553         
554         bool forceBackgroundToWhite = false;
555         if (isPrinting) {
556             if (styleToUse->printColorAdjust() == PrintColorAdjustEconomy)
557                 forceBackgroundToWhite = true;
558             if (textRenderer()->document()->settings() && textRenderer()->document()->settings()->shouldPrintBackgrounds())
559                 forceBackgroundToWhite = false;
560         }
561
562         // Make the text fill color legible against a white background
563         if (forceBackgroundToWhite)
564             textFillColor = correctedTextColor(textFillColor, Color::white);
565
566         textStrokeColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
567         
568         // Make the text stroke color legible against a white background
569         if (forceBackgroundToWhite)
570             textStrokeColor = correctedTextColor(textStrokeColor, Color::white);
571
572         emphasisMarkColor = styleToUse->visitedDependentColor(CSSPropertyWebkitTextEmphasisColor);
573         
574         // Make the text stroke color legible against a white background
575         if (forceBackgroundToWhite)
576             emphasisMarkColor = correctedTextColor(emphasisMarkColor, Color::white);
577     }
578
579     bool paintSelectedTextOnly = (paintInfo.phase == PaintPhaseSelection);
580     bool paintSelectedTextSeparately = false;
581
582     Color selectionFillColor = textFillColor;
583     Color selectionStrokeColor = textStrokeColor;
584     Color selectionEmphasisMarkColor = emphasisMarkColor;
585     float selectionStrokeWidth = textStrokeWidth;
586     const ShadowData* selectionShadow = textShadow;
587     if (haveSelection) {
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;
594         }
595
596         Color emphasisMarkForeground = paintInfo.forceBlackText ? Color::black : renderer()->selectionEmphasisMarkColor();
597         if (emphasisMarkForeground.isValid() && emphasisMarkForeground != selectionEmphasisMarkColor) {
598             if (!paintSelectedTextOnly)
599                 paintSelectedTextSeparately = true;
600             selectionEmphasisMarkColor = emphasisMarkForeground;
601         }
602
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;
609             }
610
611             float strokeWidth = pseudoStyle->textStrokeWidth();
612             if (strokeWidth != selectionStrokeWidth) {
613                 if (!paintSelectedTextOnly)
614                     paintSelectedTextSeparately = true;
615                 selectionStrokeWidth = strokeWidth;
616             }
617
618             Color stroke = paintInfo.forceBlackText ? Color::black : pseudoStyle->visitedDependentColor(CSSPropertyWebkitTextStrokeColor);
619             if (stroke != selectionStrokeColor) {
620                 if (!paintSelectedTextOnly)
621                     paintSelectedTextSeparately = true;
622                 selectionStrokeColor = stroke;
623             }
624         }
625     }
626
627     // Set our font.
628     const Font& font = styleToUse->font();
629
630     FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
631
632     if (combinedText)
633         combinedText->adjustTextOrigin(textOrigin, boxRect);
634
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) {
638 #if PLATFORM(MAC)
639         // Custom highlighters go behind everything else.
640         if (styleToUse->highlight() != nullAtom && !context->paintingDisabled())
641             paintCustomHighlight(adjustedPaintOffset, styleToUse->highlight());
642 #endif
643
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();
652
653             for (size_t index = 0; index < numUnderlines; ++index) {
654                 const CompositionUnderline& underline = underlines[index];
655
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.
660                     continue;
661
662                 if (underline.startOffset <= end()) {
663                     // underline intersects this run.  Paint the background of the underline.
664                     paintCompositionUnderlineBackground(context, boxOrigin, styleToUse, font, underline);
665
666                     if (underline.endOffset > end() + 1)
667                         // underline also runs into the next run. Bail now, no more marker advancement.
668                         break;
669                 } else
670                     // underline is completely after this run, bail.  A later run will paint it.
671                     break;
672             }
673         }
674 #endif
675
676         paintDocumentMarkers(context, boxOrigin, styleToUse, font, true);
677
678         if (haveSelection && !useCustomUnderlines)
679             paintSelection(context, boxOrigin, styleToUse, font, selectionFillColor);
680     }
681
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()));
690         }
691     }
692
693     // 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
694     int length = m_len;
695     int maximumLength;
696     const UChar* characters;
697     if (!combinedText) {
698         characters = textRenderer()->text()->characters() + m_start;
699         maximumLength = textRenderer()->textLength() - m_start;
700     } else {
701         combinedText->charactersToRender(m_start, characters, length);
702         maximumLength = length;
703     }
704
705     BufferForAppendingHyphen charactersWithHyphen;
706     TextRun textRun = constructTextRun(styleToUse, font, characters, length, maximumLength, hasHyphen() ? &charactersWithHyphen : 0);
707     if (hasHyphen())
708         length = textRun.length();
709
710     int sPos = 0;
711     int ePos = 0;
712     if (paintSelectedTextOnly || paintSelectedTextSeparately)
713         selectionStartEnd(sPos, ePos);
714
715     if (m_truncation != cNoTruncation) {
716         sPos = min<int>(sPos, m_truncation);
717         ePos = min<int>(ePos, m_truncation);
718         length = m_truncation;
719     }
720
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);
727
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);
732
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());
737         } else
738             paintTextWithShadows(context, font, textRun, nullAtom, 0, ePos, sPos, length, textOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
739
740         if (!emphasisMark.isEmpty()) {
741             updateGraphicsContext(context, emphasisMarkColor, textStrokeColor, textStrokeWidth, styleToUse->colorSpace());
742
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;
746             if (combinedText)
747                 context->concatCTM(rotation(boxRect, Clockwise));
748
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());
752             } else
753                 paintTextWithShadows(context, combinedText ? combinedText->originalFont() : font, emphasisMarkTextRun, emphasisMark, emphasisMarkOffset, ePos, sPos, length, emphasisMarkTextOrigin, boxRect, textShadow, textStrokeWidth > 0, isHorizontal());
754
755             if (combinedText)
756                 context->concatCTM(rotation(boxRect, Counterclockwise));
757         }
758     }
759
760     if ((paintSelectedTextOnly || paintSelectedTextSeparately) && sPos < ePos) {
761         // paint only the text that is selected
762         GraphicsContextStateSaver stateSaver(*context, selectionStrokeWidth > 0);
763
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());
768
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;
772             if (combinedText)
773                 context->concatCTM(rotation(boxRect, Clockwise));
774
775             paintTextWithShadows(context, combinedText ? combinedText->originalFont() : font, emphasisMarkTextRun, emphasisMark, emphasisMarkOffset, sPos, ePos, length, emphasisMarkTextOrigin, boxRect, selectionShadow, selectionStrokeWidth > 0, isHorizontal());
776
777             if (combinedText)
778                 context->concatCTM(rotation(boxRect, Counterclockwise));
779         }
780     }
781
782     // Paint decorations
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);
787     }
788
789     if (paintInfo.phase == PaintPhaseForeground) {
790         paintDocumentMarkers(context, boxOrigin, styleToUse, font, false);
791
792         if (useCustomUnderlines) {
793             const Vector<CompositionUnderline>& underlines = renderer()->frame()->editor()->customCompositionUnderlines();
794             size_t numUnderlines = underlines.size();
795
796             for (size_t index = 0; index < numUnderlines; ++index) {
797                 const CompositionUnderline& underline = underlines[index];
798
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.
803                     continue;
804                 
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.
810                         break;
811                 } else
812                     // underline is completely after this run, bail.  A later run will paint it.
813                     break;
814             }
815         }
816     }
817     
818     if (shouldRotate)
819         context->concatCTM(rotation(boxRect, Counterclockwise));
820 }
821
822 void InlineTextBox::selectionStartEnd(int& sPos, int& ePos)
823 {
824     int startPos, endPos;
825     if (renderer()->selectionState() == RenderObject::SelectionInside) {
826         startPos = 0;
827         endPos = textRenderer()->textLength();
828     } else {
829         textRenderer()->selectionStartEnd(startPos, endPos);
830         if (renderer()->selectionState() == RenderObject::SelectionStart)
831             endPos = textRenderer()->textLength();
832         else if (renderer()->selectionState() == RenderObject::SelectionEnd)
833             startPos = 0;
834     }
835
836     sPos = max(startPos - m_start, 0);
837     ePos = min(endPos - m_start, (int)m_len);
838 }
839
840 void alignSelectionRectToDevicePixels(FloatRect& rect)
841 {
842     float maxX = floorf(rect.maxX());
843     rect.setX(floorf(rect.x()));
844     rect.setWidth(roundf(maxX - rect.x()));
845 }
846
847 void InlineTextBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, Color textColor)
848 {
849     if (context->paintingDisabled())
850         return;
851
852     // See if we have a selection to paint at all.
853     int sPos, ePos;
854     selectionStartEnd(sPos, ePos);
855     if (sPos >= ePos)
856         return;
857
858     Color c = renderer()->selectionBackgroundColor();
859     if (!c.isValid() || c.alpha() == 0)
860         return;
861
862     // If the text color ends up being the same as the selection background, invert the selection
863     // background.
864     if (textColor == c)
865         c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
866
867     GraphicsContextStateSaver stateSaver(*context);
868     updateGraphicsContext(context, c, c, 0, style->colorSpace());  // Don't draw text at all!
869     
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;
874
875     BufferForAppendingHyphen charactersWithHyphen;
876     bool respectHyphen = ePos == length && hasHyphen();
877     TextRun textRun = constructTextRun(style, font, characters, length, textRenderer()->textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
878     if (respectHyphen)
879         ePos = textRun.length();
880
881     LayoutUnit selectionBottom = root()->selectionBottom();
882     LayoutUnit selectionTop = root()->selectionTopAdjustedForPrecedingBlock();
883
884     int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
885     int selHeight = max(0, roundToInt(selectionBottom - selectionTop));
886
887     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
888     FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
889     alignSelectionRectToDevicePixels(clipRect);
890
891     context->clip(clipRect);
892
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);
898 #else
899     context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
900 #endif
901 }
902
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)
905 {
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);
912
913     if (sPos >= ePos)
914         return;
915
916     GraphicsContextStateSaver stateSaver(*context);
917
918     Color c = underline.backgroundColor;
919     if (!c.isValid())
920         return;
921
922     updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
923
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);
928 }
929 #endif
930
931 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, int startPos, int endPos)
932 {
933     int offset = m_start;
934     int sPos = max(startPos - offset, 0);
935     int ePos = min(endPos - offset, (int)m_len);
936
937     if (sPos >= ePos)
938         return;
939
940     GraphicsContextStateSaver stateSaver(*context);
941
942     Color c = Color(225, 221, 85);
943     
944     updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
945
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);
950 }
951
952 #if PLATFORM(MAC)
953
954 void InlineTextBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type)
955 {
956     Frame* frame = renderer()->frame();
957     if (!frame)
958         return;
959     Page* page = frame->page();
960     if (!page)
961         return;
962
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());
966
967     page->chrome()->client()->paintCustomHighlight(renderer()->node(), type, textRect, rootRect, true, false);
968 }
969
970 #endif
971
972 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, int deco, const ShadowData* shadow)
973 {
974     if (m_truncation == cFullTruncation)
975         return;
976
977     FloatPoint localOrigin = boxOrigin;
978
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);
984     }
985     
986     // Get the text decoration colors.
987     Color underline, overline, linethrough;
988     renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, isFirstLineStyle());
989     
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.
993
994     bool linesAreOpaque = !isPrinting && (!(deco & UNDERLINE) || underline.alpha() == 255) && (!(deco & OVERLINE) || overline.alpha() == 255) && (!(deco & LINE_THROUGH) || linethrough.alpha() == 255);
995
996     RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
997     int baseline = styleToUse->fontMetrics().ascent();
998
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());
1011         }
1012         context->save();
1013         context->clip(clipRect);
1014         extraOffset += baseline + 2;
1015         localOrigin.move(0, extraOffset);
1016         setClip = true;
1017     }
1018
1019     ColorSpace colorSpace = renderer()->style()->colorSpace();
1020     bool setShadow = false;
1021     
1022     do {
1023         if (shadow) {
1024             if (!shadow->next()) {
1025                 // The last set of lines paints normally inside the clip.
1026                 localOrigin.move(0, -extraOffset);
1027                 extraOffset = 0;
1028             }
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);
1032             setShadow = true;
1033             shadow = shadow->next();
1034         }
1035
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);
1041         }
1042         if (deco & OVERLINE) {
1043             context->setStrokeColor(overline, colorSpace);
1044             context->setStrokeStyle(SolidStroke);
1045             context->drawLineForText(localOrigin, width, isPrinting);
1046         }
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);
1051         }
1052     } while (shadow);
1053
1054     if (setClip)
1055         context->restore();
1056     else if (setShadow)
1057         context->clearShadow();
1058 }
1059
1060 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1061 {
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;
1071     default:
1072         ASSERT_NOT_REACHED();
1073         return GraphicsContext::DocumentMarkerSpellingLineStyle;
1074     }
1075 }
1076
1077 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1078 {
1079     // Never print spelling/grammar markers (5327887)
1080     if (textRenderer()->document()->printing())
1081         return;
1082
1083     if (m_truncation == cFullTruncation)
1084         return;
1085
1086     float start = 0; // start of line to draw, relative to tx
1087     float width = m_logicalWidth; // how much line to draw
1088
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;
1097
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);
1102         
1103         if (m_truncation != cNoTruncation)
1104             endPosition = min<int>(endPosition, m_truncation);
1105
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);
1111
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();
1116         
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);
1123         }
1124     }
1125     
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;
1139     } else {
1140         // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1141         underlineOffset = baseline + 2;
1142     }
1143     pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1144 }
1145
1146 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1147 {
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();
1152
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);
1156
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);
1161     
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);
1171     }
1172 }
1173
1174 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, RenderStyle* style, const Font& font)
1175 {
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();
1179     
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);
1184     
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);
1189 }
1190     
1191 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1192 {
1193     if (!renderer()->node())
1194         return;
1195
1196     Vector<DocumentMarker*> markers = renderer()->document()->markers()->markersFor(renderer()->node());
1197     Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1198
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;
1203         
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:
1211                 if (background)
1212                     continue;
1213                 break;
1214             case DocumentMarker::TextMatch:
1215                 if (!background)
1216                     continue;
1217                 break;
1218             default:
1219                 continue;
1220         }
1221
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.
1225             continue;
1226         
1227         if (marker->startOffset() > end())
1228             // marker is completely after this run, bail.  A later run will paint it.
1229             break;
1230         
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);
1237                 break;
1238             case DocumentMarker::Grammar:
1239                 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1240                 break;
1241             case DocumentMarker::TextMatch:
1242                 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1243                 break;
1244             case DocumentMarker::Replacement:
1245                 computeRectForReplacementMarker(marker, style, font);
1246                 break;
1247             default:
1248                 ASSERT_NOT_REACHED();
1249         }
1250
1251     }
1252 }
1253
1254 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1255 {
1256     if (m_truncation == cFullTruncation)
1257         return;
1258     
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());
1268     }
1269     if (paintEnd != underline.endOffset) {      // end points at the last char, not past it
1270         paintEnd = min(paintEnd, (unsigned)underline.endOffset);
1271         useWholeWidth = false;
1272     }
1273     if (m_truncation != cNoTruncation) {
1274         paintEnd = min(paintEnd, (unsigned)m_start + m_truncation);
1275         useWholeWidth = false;
1276     }
1277     if (!useWholeWidth) {
1278         width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLineStyle());
1279     }
1280
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)
1287         lineThickness = 2;
1288
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.
1292     start += 1;
1293     width -= 2;
1294 #endif
1295
1296
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());
1300 }
1301
1302 int InlineTextBox::caretMinOffset() const
1303 {
1304     return m_start;
1305 }
1306
1307 int InlineTextBox::caretMaxOffset() const
1308 {
1309     return m_start + m_len;
1310 }
1311
1312 float InlineTextBox::textPos() const
1313 {
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)
1317         return 0;
1318     return logicalLeft() - root()->logicalLeft();
1319 }
1320
1321 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1322 {
1323     if (isLineBreak())
1324         return 0;
1325
1326     if (lineOffset - logicalLeft() > logicalWidth())
1327         return isLeftToRightDirection() ? len() : 0;
1328     if (lineOffset - logicalLeft() < 0)
1329         return isLeftToRightDirection() ? 0 : len();
1330
1331     FontCachePurgePreventer fontCachePurgePreventer;
1332
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);
1337 }
1338
1339 float InlineTextBox::positionForOffset(int offset) const
1340 {
1341     ASSERT(offset >= m_start);
1342     ASSERT(offset <= m_start + m_len);
1343
1344     if (isLineBreak())
1345         return logicalLeft();
1346
1347     FontCachePurgePreventer fontCachePurgePreventer;
1348
1349     RenderText* text = toRenderText(renderer());
1350     RenderStyle* styleToUse = text->style(isFirstLineStyle());
1351     ASSERT(styleToUse);
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();
1357 }
1358
1359 bool InlineTextBox::containsCaretOffset(int offset) const
1360 {
1361     // Offsets before the box are never "in".
1362     if (offset < m_start)
1363         return false;
1364
1365     int pastEnd = m_start + m_len;
1366
1367     // Offsets inside the box (not at either edge) are always "in".
1368     if (offset < pastEnd)
1369         return true;
1370
1371     // Offsets outside the box are always "out".
1372     if (offset > pastEnd)
1373         return false;
1374
1375     // Offsets at the end are "out" for line breaks (they are on the next line).
1376     if (isLineBreak())
1377         return false;
1378
1379     // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1380     return true;
1381 }
1382
1383 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1384 {
1385     ASSERT(style);
1386
1387     RenderText* textRenderer = this->textRenderer();
1388     ASSERT(textRenderer);
1389     ASSERT(textRenderer->characters());
1390
1391     return constructTextRun(style, font, textRenderer->characters() + start(), len(), textRenderer->textLength() - start(), charactersWithHyphen);
1392 }
1393
1394 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, const UChar* characters, int length, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1395 {
1396     ASSERT(style);
1397
1398     RenderText* textRenderer = this->textRenderer();
1399     ASSERT(textRenderer);
1400
1401     if (charactersWithHyphen) {
1402         adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, characters, length);
1403         maximumLength = length;
1404     }
1405
1406     ASSERT(maximumLength >= length);
1407
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));
1412
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());
1416     return run;
1417 }
1418
1419 #ifndef NDEBUG
1420
1421 const char* InlineTextBox::boxName() const
1422 {
1423     return "InlineTextBox";
1424 }
1425
1426 void InlineTextBox::showBox(int printedCharacters) const
1427 {
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++)
1435         fputc(' ', stderr);
1436     printedCharacters = fprintf(stderr, "\t%s %p", obj->renderName(), obj);
1437     const int rendererCharacterOffset = 24;
1438     for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1439         fputc(' ', stderr);
1440     fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1441 }
1442
1443 #endif
1444
1445 } // namespace WebCore