Blocked painting of selection for inline inputbox
[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 ENABLE(TIZEN_WEBKIT2_TEXT_SELECTION_NOT_PAINT_SELECTION_FOR_INPUTBOX)
856     Node* shadowAncestor = 0;
857     if (renderer() && renderer()->node())
858         shadowAncestor = renderer()->node()->shadowAncestorNode();
859
860     if (shadowAncestor && (shadowAncestor->renderer()->isTextField() || shadowAncestor->renderer()->isTextArea())) {
861         if (selectionState() != RenderObject::SelectionBoth) {
862             RenderObject* startObj = textRenderer()->view()->selectionStart();
863             RenderObject* endObj = textRenderer()->view()->selectionEnd();
864             if (!(startObj->node()->isInShadowTree() && endObj->node()->isInShadowTree()))
865                 return;
866         }
867     }
868 #endif
869
870     if (sPos >= ePos)
871         return;
872
873     Color c = renderer()->selectionBackgroundColor();
874     if (!c.isValid() || c.alpha() == 0)
875         return;
876
877     // If the text color ends up being the same as the selection background, invert the selection
878     // background.
879     if (textColor == c)
880         c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
881
882     GraphicsContextStateSaver stateSaver(*context);
883     updateGraphicsContext(context, c, c, 0, style->colorSpace());  // Don't draw text at all!
884     
885     // If the text is truncated, let the thing being painted in the truncation
886     // draw its own highlight.
887     int length = m_truncation != cNoTruncation ? m_truncation : m_len;
888     const UChar* characters = textRenderer()->text()->characters() + m_start;
889
890     BufferForAppendingHyphen charactersWithHyphen;
891     bool respectHyphen = ePos == length && hasHyphen();
892     TextRun textRun = constructTextRun(style, font, characters, length, textRenderer()->textLength() - m_start, respectHyphen ? &charactersWithHyphen : 0);
893     if (respectHyphen)
894         ePos = textRun.length();
895
896     LayoutUnit selectionBottom = root()->selectionBottom();
897     LayoutUnit selectionTop = root()->selectionTopAdjustedForPrecedingBlock();
898
899     int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - selectionTop);
900     int selHeight = max(0, roundToInt(selectionBottom - selectionTop));
901
902     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
903     FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, selHeight));
904     alignSelectionRectToDevicePixels(clipRect);
905
906     context->clip(clipRect);
907
908 #if ENABLE(TIZEN_PAINT_SELECTION_ANTIALIAS_NONE)
909     bool antialias = context->shouldAntialias();
910     context->setShouldAntialias(false);
911     context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
912     context->setShouldAntialias(antialias);
913 #else
914     context->drawHighlightForText(font, textRun, localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
915 #endif
916 }
917
918 #if ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
919 void InlineTextBox::paintCompositionUnderlineBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, const CompositionUnderline underline)
920 {
921     int offset = m_start;
922     int sOffset = static_cast<int>(underline.startOffset);
923     int eOffset = static_cast<int>(underline.endOffset);
924     int length = static_cast<int>(m_len);
925     int sPos = max(sOffset - offset, 0);
926     int ePos = min(eOffset - offset, length);
927
928     if (sPos >= ePos)
929         return;
930
931     GraphicsContextStateSaver stateSaver(*context);
932
933     Color c = underline.backgroundColor;
934     if (!c.isValid())
935         return;
936
937     updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
938
939     int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
940     int selHeight = selectionHeight();
941     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
942     context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
943 }
944 #endif
945
946 void InlineTextBox::paintCompositionBackground(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, int startPos, int endPos)
947 {
948     int offset = m_start;
949     int sPos = max(startPos - offset, 0);
950     int ePos = min(endPos - offset, (int)m_len);
951
952     if (sPos >= ePos)
953         return;
954
955     GraphicsContextStateSaver stateSaver(*context);
956
957     Color c = Color(225, 221, 85);
958     
959     updateGraphicsContext(context, c, c, 0, style->colorSpace()); // Don't draw text at all!
960
961     int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
962     int selHeight = selectionHeight();
963     FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
964     context->drawHighlightForText(font, constructTextRun(style, font), localOrigin, selHeight, c, style->colorSpace(), sPos, ePos);
965 }
966
967 #if PLATFORM(MAC)
968
969 void InlineTextBox::paintCustomHighlight(const LayoutPoint& paintOffset, const AtomicString& type)
970 {
971     Frame* frame = renderer()->frame();
972     if (!frame)
973         return;
974     Page* page = frame->page();
975     if (!page)
976         return;
977
978     RootInlineBox* r = root();
979     FloatRect rootRect(paintOffset.x() + r->x(), paintOffset.y() + selectionTop(), r->logicalWidth(), selectionHeight());
980     FloatRect textRect(paintOffset.x() + x(), rootRect.y(), logicalWidth(), rootRect.height());
981
982     page->chrome()->client()->paintCustomHighlight(renderer()->node(), type, textRect, rootRect, true, false);
983 }
984
985 #endif
986
987 void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, int deco, const ShadowData* shadow)
988 {
989     if (m_truncation == cFullTruncation)
990         return;
991
992     FloatPoint localOrigin = boxOrigin;
993
994     float width = m_logicalWidth;
995     if (m_truncation != cNoTruncation) {
996         width = toRenderText(renderer())->width(m_start, m_truncation, textPos(), isFirstLineStyle());
997         if (!isLeftToRightDirection())
998             localOrigin.move(m_logicalWidth - width, 0);
999     }
1000     
1001     // Get the text decoration colors.
1002     Color underline, overline, linethrough;
1003     renderer()->getTextDecorationColors(deco, underline, overline, linethrough, true, isFirstLineStyle());
1004     
1005     // Use a special function for underlines to get the positioning exactly right.
1006     bool isPrinting = textRenderer()->document()->printing();
1007     context->setStrokeThickness(1.0f); // FIXME: We should improve this rule and not always just assume 1.
1008
1009     bool linesAreOpaque = !isPrinting && (!(deco & UNDERLINE) || underline.alpha() == 255) && (!(deco & OVERLINE) || overline.alpha() == 255) && (!(deco & LINE_THROUGH) || linethrough.alpha() == 255);
1010
1011     RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
1012     int baseline = styleToUse->fontMetrics().ascent();
1013
1014     bool setClip = false;
1015     int extraOffset = 0;
1016     if (!linesAreOpaque && shadow && shadow->next()) {
1017         FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
1018         for (const ShadowData* s = shadow; s; s = s->next()) {
1019             FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
1020             shadowRect.inflate(s->blur());
1021             int shadowX = isHorizontal() ? s->x() : s->y();
1022             int shadowY = isHorizontal() ? s->y() : -s->x();
1023             shadowRect.move(shadowX, shadowY);
1024             clipRect.unite(shadowRect);
1025             extraOffset = max(extraOffset, max(0, shadowY) + s->blur());
1026         }
1027         context->save();
1028         context->clip(clipRect);
1029         extraOffset += baseline + 2;
1030         localOrigin.move(0, extraOffset);
1031         setClip = true;
1032     }
1033
1034     ColorSpace colorSpace = renderer()->style()->colorSpace();
1035     bool setShadow = false;
1036     
1037     do {
1038         if (shadow) {
1039             if (!shadow->next()) {
1040                 // The last set of lines paints normally inside the clip.
1041                 localOrigin.move(0, -extraOffset);
1042                 extraOffset = 0;
1043             }
1044             int shadowX = isHorizontal() ? shadow->x() : shadow->y();
1045             int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
1046             context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color(), colorSpace);
1047             setShadow = true;
1048             shadow = shadow->next();
1049         }
1050
1051         if (deco & UNDERLINE) {
1052             context->setStrokeColor(underline, colorSpace);
1053             context->setStrokeStyle(SolidStroke);
1054             // Leave one pixel of white between the baseline and the underline.
1055             context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + baseline + 1), width, isPrinting);
1056         }
1057         if (deco & OVERLINE) {
1058             context->setStrokeColor(overline, colorSpace);
1059             context->setStrokeStyle(SolidStroke);
1060             context->drawLineForText(localOrigin, width, isPrinting);
1061         }
1062         if (deco & LINE_THROUGH) {
1063             context->setStrokeColor(linethrough, colorSpace);
1064             context->setStrokeStyle(SolidStroke);
1065             context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + 2 * baseline / 3), width, isPrinting);
1066         }
1067     } while (shadow);
1068
1069     if (setClip)
1070         context->restore();
1071     else if (setShadow)
1072         context->clearShadow();
1073 }
1074
1075 static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
1076 {
1077     switch (markerType) {
1078     case DocumentMarker::Spelling:
1079         return GraphicsContext::DocumentMarkerSpellingLineStyle;
1080     case DocumentMarker::Grammar:
1081         return GraphicsContext::DocumentMarkerGrammarLineStyle;
1082     case DocumentMarker::CorrectionIndicator:
1083         return GraphicsContext::DocumentMarkerAutocorrectionReplacementLineStyle;
1084     case DocumentMarker::DictationAlternatives:
1085         return GraphicsContext::DocumentMarkerDictationAlternativesLineStyle;
1086     default:
1087         ASSERT_NOT_REACHED();
1088         return GraphicsContext::DocumentMarkerSpellingLineStyle;
1089     }
1090 }
1091
1092 void InlineTextBox::paintDocumentMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font, bool grammar)
1093 {
1094     // Never print spelling/grammar markers (5327887)
1095     if (textRenderer()->document()->printing())
1096         return;
1097
1098     if (m_truncation == cFullTruncation)
1099         return;
1100
1101     float start = 0; // start of line to draw, relative to tx
1102     float width = m_logicalWidth; // how much line to draw
1103
1104     // Determine whether we need to measure text
1105     bool markerSpansWholeBox = true;
1106     if (m_start <= (int)marker->startOffset())
1107         markerSpansWholeBox = false;
1108     if ((end() + 1) != marker->endOffset()) // end points at the last char, not past it
1109         markerSpansWholeBox = false;
1110     if (m_truncation != cNoTruncation)
1111         markerSpansWholeBox = false;
1112
1113     bool isDictationMarker = marker->type() == DocumentMarker::DictationAlternatives;
1114     if (!markerSpansWholeBox || grammar || isDictationMarker) {
1115         int startPosition = max<int>(marker->startOffset() - m_start, 0);
1116         int endPosition = min<int>(marker->endOffset() - m_start, m_len);
1117         
1118         if (m_truncation != cNoTruncation)
1119             endPosition = min<int>(endPosition, m_truncation);
1120
1121         // Calculate start & width
1122         int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1123         int selHeight = selectionHeight();
1124         FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
1125         TextRun run = constructTextRun(style, font);
1126
1127         // FIXME: Convert the document markers to float rects.
1128         IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
1129         start = markerRect.x() - startPoint.x();
1130         width = markerRect.width();
1131         
1132         // Store rendered rects for bad grammar markers, so we can hit-test against it elsewhere in order to
1133         // display a toolTip. We don't do this for misspelling markers.
1134         if (grammar || isDictationMarker) {
1135             markerRect.move(-boxOrigin.x(), -boxOrigin.y());
1136             markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1137             toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1138         }
1139     }
1140     
1141     // IMPORTANT: The misspelling underline is not considered when calculating the text bounds, so we have to
1142     // make sure to fit within those bounds.  This means the top pixel(s) of the underline will overlap the
1143     // bottom pixel(s) of the glyphs in smaller font sizes.  The alternatives are to increase the line spacing (bad!!)
1144     // or decrease the underline thickness.  The overlap is actually the most useful, and matches what AppKit does.
1145     // So, we generally place the underline at the bottom of the text, but in larger fonts that's not so good so
1146     // we pin to two pixels under the baseline.
1147     int lineThickness = cMisspellingLineThickness;
1148     int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1149     int descent = logicalHeight() - baseline;
1150     int underlineOffset;
1151     if (descent <= (2 + lineThickness)) {
1152         // Place the underline at the very bottom of the text in small/medium fonts.
1153         underlineOffset = logicalHeight() - lineThickness;
1154     } else {
1155         // In larger fonts, though, place the underline up near the baseline to prevent a big gap.
1156         underlineOffset = baseline + 2;
1157     }
1158     pt->drawLineForDocumentMarker(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + underlineOffset), width, lineStyleForMarkerType(marker->type()));
1159 }
1160
1161 void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint& boxOrigin, DocumentMarker* marker, RenderStyle* style, const Font& font)
1162 {
1163     // Use same y positioning and height as for selection, so that when the selection and this highlight are on
1164     // the same word there are no pieces sticking out.
1165     int deltaY = renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
1166     int selHeight = selectionHeight();
1167
1168     int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1169     int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1170     TextRun run = constructTextRun(style, font);
1171
1172     // Always compute and store the rect associated with this marker. The computed rect is in absolute coordinates.
1173     IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, IntPoint(x(), selectionTop()), selHeight, sPos, ePos));
1174     markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1175     toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1176     
1177     // Optionally highlight the text
1178     if (renderer()->frame()->editor()->markedTextMatchesAreHighlighted()) {
1179         Color color = marker->activeMatch() ?
1180             renderer()->theme()->platformActiveTextSearchHighlightColor() :
1181             renderer()->theme()->platformInactiveTextSearchHighlightColor();
1182         GraphicsContextStateSaver stateSaver(*pt);
1183         updateGraphicsContext(pt, color, color, 0, style->colorSpace());  // Don't draw text at all!
1184         pt->clip(FloatRect(boxOrigin.x(), boxOrigin.y() - deltaY, m_logicalWidth, selHeight));
1185         pt->drawHighlightForText(font, run, FloatPoint(boxOrigin.x(), boxOrigin.y() - deltaY), selHeight, color, style->colorSpace(), sPos, ePos);
1186     }
1187 }
1188
1189 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, RenderStyle* style, const Font& font)
1190 {
1191     // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
1192     int top = selectionTop();
1193     int h = selectionHeight();
1194     
1195     int sPos = max(marker->startOffset() - m_start, (unsigned)0);
1196     int ePos = min(marker->endOffset() - m_start, (unsigned)m_len);
1197     TextRun run = constructTextRun(style, font);
1198     IntPoint startPoint = IntPoint(x(), top);
1199     
1200     // Compute and store the rect associated with this marker.
1201     IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, h, sPos, ePos));
1202     markerRect = renderer()->localToAbsoluteQuad(FloatRect(markerRect)).enclosingBoundingBox();
1203     toRenderedDocumentMarker(marker)->setRenderedRect(markerRect);
1204 }
1205     
1206 void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font, bool background)
1207 {
1208     if (!renderer()->node())
1209         return;
1210
1211     Vector<DocumentMarker*> markers = renderer()->document()->markers()->markersFor(renderer()->node());
1212     Vector<DocumentMarker*>::const_iterator markerIt = markers.begin();
1213
1214     // Give any document markers that touch this run a chance to draw before the text has been drawn.
1215     // Note end() points at the last char, not one past it like endOffset and ranges do.
1216     for ( ; markerIt != markers.end(); markerIt++) {
1217         DocumentMarker* marker = *markerIt;
1218         
1219         // Paint either the background markers or the foreground markers, but not both
1220         switch (marker->type()) {
1221             case DocumentMarker::Grammar:
1222             case DocumentMarker::Spelling:
1223             case DocumentMarker::CorrectionIndicator:
1224             case DocumentMarker::Replacement:
1225             case DocumentMarker::DictationAlternatives:
1226                 if (background)
1227                     continue;
1228                 break;
1229             case DocumentMarker::TextMatch:
1230                 if (!background)
1231                     continue;
1232                 break;
1233             default:
1234                 continue;
1235         }
1236
1237         if (marker->endOffset() <= start())
1238             // marker is completely before this run.  This might be a marker that sits before the
1239             // first run we draw, or markers that were within runs we skipped due to truncation.
1240             continue;
1241         
1242         if (marker->startOffset() > end())
1243             // marker is completely after this run, bail.  A later run will paint it.
1244             break;
1245         
1246         // marker intersects this run.  Paint it.
1247         switch (marker->type()) {
1248             case DocumentMarker::Spelling:
1249             case DocumentMarker::CorrectionIndicator:
1250             case DocumentMarker::DictationAlternatives:
1251                 paintDocumentMarker(pt, boxOrigin, marker, style, font, false);
1252                 break;
1253             case DocumentMarker::Grammar:
1254                 paintDocumentMarker(pt, boxOrigin, marker, style, font, true);
1255                 break;
1256             case DocumentMarker::TextMatch:
1257                 paintTextMatchMarker(pt, boxOrigin, marker, style, font);
1258                 break;
1259             case DocumentMarker::Replacement:
1260                 computeRectForReplacementMarker(marker, style, font);
1261                 break;
1262             default:
1263                 ASSERT_NOT_REACHED();
1264         }
1265
1266     }
1267 }
1268
1269 void InlineTextBox::paintCompositionUnderline(GraphicsContext* ctx, const FloatPoint& boxOrigin, const CompositionUnderline& underline)
1270 {
1271     if (m_truncation == cFullTruncation)
1272         return;
1273     
1274     float start = 0; // start of line to draw, relative to tx
1275     float width = m_logicalWidth; // how much line to draw
1276     bool useWholeWidth = true;
1277     unsigned paintStart = m_start;
1278     unsigned paintEnd = end() + 1; // end points at the last char, not past it
1279     if (paintStart <= underline.startOffset) {
1280         paintStart = underline.startOffset;
1281         useWholeWidth = false;
1282         start = toRenderText(renderer())->width(m_start, paintStart - m_start, textPos(), isFirstLineStyle());
1283     }
1284     if (paintEnd != underline.endOffset) {      // end points at the last char, not past it
1285         paintEnd = min(paintEnd, (unsigned)underline.endOffset);
1286         useWholeWidth = false;
1287     }
1288     if (m_truncation != cNoTruncation) {
1289         paintEnd = min(paintEnd, (unsigned)m_start + m_truncation);
1290         useWholeWidth = false;
1291     }
1292     if (!useWholeWidth) {
1293         width = toRenderText(renderer())->width(paintStart, paintEnd - paintStart, textPos() + start, isFirstLineStyle());
1294     }
1295
1296     // Thick marked text underlines are 2px thick as long as there is room for the 2px line under the baseline.
1297     // All other marked text underlines are 1px thick.
1298     // If there's not enough space the underline will touch or overlap characters.
1299     int lineThickness = 1;
1300     int baseline = renderer()->style(isFirstLineStyle())->fontMetrics().ascent();
1301     if (underline.thick && logicalHeight() - baseline >= 2)
1302         lineThickness = 2;
1303
1304 #if !ENABLE(TIZEN_WEBKIT2_SUPPORT_JAPANESE_IME)
1305     // We need to have some space between underlines of subsequent clauses, because some input methods do not use different underline styles for those.
1306     // We make each line shorter, which has a harmless side effect of shortening the first and last clauses, too.
1307     start += 1;
1308     width -= 2;
1309 #endif
1310
1311
1312     ctx->setStrokeColor(underline.color, renderer()->style()->colorSpace());
1313     ctx->setStrokeThickness(lineThickness);
1314     ctx->drawLineForText(FloatPoint(boxOrigin.x() + start, boxOrigin.y() + logicalHeight() - lineThickness), width, textRenderer()->document()->printing());
1315 }
1316
1317 int InlineTextBox::caretMinOffset() const
1318 {
1319     return m_start;
1320 }
1321
1322 int InlineTextBox::caretMaxOffset() const
1323 {
1324     return m_start + m_len;
1325 }
1326
1327 float InlineTextBox::textPos() const
1328 {
1329     // When computing the width of a text run, RenderBlock::computeInlineDirectionPositionsForLine() doesn't include the actual offset
1330     // from the containing block edge in its measurement. textPos() should be consistent so the text are rendered in the same width.
1331     if (logicalLeft() == 0)
1332         return 0;
1333     return logicalLeft() - root()->logicalLeft();
1334 }
1335
1336 int InlineTextBox::offsetForPosition(float lineOffset, bool includePartialGlyphs) const
1337 {
1338     if (isLineBreak())
1339         return 0;
1340
1341     if (lineOffset - logicalLeft() > logicalWidth())
1342         return isLeftToRightDirection() ? len() : 0;
1343     if (lineOffset - logicalLeft() < 0)
1344         return isLeftToRightDirection() ? 0 : len();
1345
1346     FontCachePurgePreventer fontCachePurgePreventer;
1347
1348     RenderText* text = toRenderText(renderer());
1349     RenderStyle* style = text->style(isFirstLineStyle());
1350     const Font& font = style->font();
1351     return font.offsetForPosition(constructTextRun(style, font), lineOffset - logicalLeft(), includePartialGlyphs);
1352 }
1353
1354 float InlineTextBox::positionForOffset(int offset) const
1355 {
1356     ASSERT(offset >= m_start);
1357     ASSERT(offset <= m_start + m_len);
1358
1359     if (isLineBreak())
1360         return logicalLeft();
1361
1362     FontCachePurgePreventer fontCachePurgePreventer;
1363
1364     RenderText* text = toRenderText(renderer());
1365     RenderStyle* styleToUse = text->style(isFirstLineStyle());
1366     ASSERT(styleToUse);
1367     const Font& font = styleToUse->font();
1368     int from = !isLeftToRightDirection() ? offset - m_start : 0;
1369     int to = !isLeftToRightDirection() ? m_len : offset - m_start;
1370     // FIXME: Do we need to add rightBearing here?
1371     return font.selectionRectForText(constructTextRun(styleToUse, font), IntPoint(logicalLeft(), 0), 0, from, to).maxX();
1372 }
1373
1374 bool InlineTextBox::containsCaretOffset(int offset) const
1375 {
1376     // Offsets before the box are never "in".
1377     if (offset < m_start)
1378         return false;
1379
1380     int pastEnd = m_start + m_len;
1381
1382     // Offsets inside the box (not at either edge) are always "in".
1383     if (offset < pastEnd)
1384         return true;
1385
1386     // Offsets outside the box are always "out".
1387     if (offset > pastEnd)
1388         return false;
1389
1390     // Offsets at the end are "out" for line breaks (they are on the next line).
1391     if (isLineBreak())
1392         return false;
1393
1394     // Offsets at the end are "in" for normal boxes (but the caller has to check affinity).
1395     return true;
1396 }
1397
1398 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, BufferForAppendingHyphen* charactersWithHyphen) const
1399 {
1400     ASSERT(style);
1401
1402     RenderText* textRenderer = this->textRenderer();
1403     ASSERT(textRenderer);
1404     ASSERT(textRenderer->characters());
1405
1406     return constructTextRun(style, font, textRenderer->characters() + start(), len(), textRenderer->textLength() - start(), charactersWithHyphen);
1407 }
1408
1409 TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, const UChar* characters, int length, int maximumLength, BufferForAppendingHyphen* charactersWithHyphen) const
1410 {
1411     ASSERT(style);
1412
1413     RenderText* textRenderer = this->textRenderer();
1414     ASSERT(textRenderer);
1415
1416     if (charactersWithHyphen) {
1417         adjustCharactersAndLengthForHyphen(*charactersWithHyphen, style, characters, length);
1418         maximumLength = length;
1419     }
1420
1421     ASSERT(maximumLength >= length);
1422
1423     TextRun run(characters, length, textPos(), expansion(), expansionBehavior(), direction(), dirOverride() || style->rtlOrdering() == VisualOrder, !textRenderer->canUseSimpleFontCodePath());
1424     run.setTabSize(!style->collapseWhiteSpace(), style->tabSize());
1425     if (textRunNeedsRenderingContext(font))
1426         run.setRenderingContext(SVGTextRunRenderingContext::create(textRenderer));
1427
1428     // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
1429     run.setCharactersLength(maximumLength);
1430     ASSERT(run.charactersLength() >= run.length());
1431     return run;
1432 }
1433
1434 #ifndef NDEBUG
1435
1436 const char* InlineTextBox::boxName() const
1437 {
1438     return "InlineTextBox";
1439 }
1440
1441 void InlineTextBox::showBox(int printedCharacters) const
1442 {
1443     const RenderText* obj = toRenderText(renderer());
1444     String value = obj->text();
1445     value = value.substring(start(), len());
1446     value.replaceWithLiteral('\\', "\\\\");
1447     value.replaceWithLiteral('\n', "\\n");
1448     printedCharacters += fprintf(stderr, "%s\t%p", boxName(), this);
1449     for (; printedCharacters < showTreeCharacterOffset; printedCharacters++)
1450         fputc(' ', stderr);
1451     printedCharacters = fprintf(stderr, "\t%s %p", obj->renderName(), obj);
1452     const int rendererCharacterOffset = 24;
1453     for (; printedCharacters < rendererCharacterOffset; printedCharacters++)
1454         fputc(' ', stderr);
1455     fprintf(stderr, "(%d,%d) \"%s\"\n", start(), start() + len(), value.utf8().data());
1456 }
1457
1458 #endif
1459
1460 } // namespace WebCore