1/**
2 * Copyright (C) 2007 Rob Buis <buis@kde.org>
3 * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
4 * Copyright (C) Research In Motion Limited 2010. 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#include "config.h"
23#include "core/rendering/svg/SVGInlineTextBox.h"
24
25#include "core/page/Frame.h"
26#include "core/page/FrameView.h"
27#include "core/platform/FloatConversion.h"
28#include "core/platform/graphics/DrawLooper.h"
29#include "core/platform/graphics/FontCache.h"
30#include "core/platform/graphics/GraphicsContextStateSaver.h"
31#include "core/rendering/HitTestResult.h"
32#include "core/rendering/InlineFlowBox.h"
33#include "core/rendering/PointerEventsHitRules.h"
34#include "core/rendering/svg/RenderSVGInlineText.h"
35#include "core/rendering/svg/RenderSVGResource.h"
36#include "core/rendering/svg/RenderSVGResourceSolidColor.h"
37#include "core/rendering/svg/SVGResourcesCache.h"
38#include "core/rendering/svg/SVGTextRunRenderingContext.h"
39
40using namespace std;
41
42namespace WebCore {
43
44struct ExpectedSVGInlineTextBoxSize : public InlineTextBox {
45    float float1;
46    uint32_t bitfields : 5;
47    void* pointer;
48    Vector<SVGTextFragment> vector;
49};
50
51COMPILE_ASSERT(sizeof(SVGInlineTextBox) == sizeof(ExpectedSVGInlineTextBoxSize), SVGInlineTextBox_is_not_of_expected_size);
52
53SVGInlineTextBox::SVGInlineTextBox(RenderObject* object)
54    : InlineTextBox(object)
55    , m_logicalHeight(0)
56    , m_paintingResourceMode(ApplyToDefaultMode)
57    , m_startsNewTextChunk(false)
58    , m_paintingResource(0)
59{
60}
61
62void SVGInlineTextBox::dirtyLineBoxes()
63{
64    InlineTextBox::dirtyLineBoxes();
65
66    // Clear the now stale text fragments
67    clearTextFragments();
68
69    // And clear any following text fragments as the text on which they
70    // depend may now no longer exist, or glyph positions may be wrong
71    InlineTextBox* nextBox = nextTextBox();
72    if (nextBox)
73        nextBox->dirtyLineBoxes();
74}
75
76int SVGInlineTextBox::offsetForPosition(float, bool) const
77{
78    // SVG doesn't use the standard offset <-> position selection system, as it's not suitable for SVGs complex needs.
79    // vertical text selection, inline boxes spanning multiple lines (contrary to HTML, etc.)
80    ASSERT_NOT_REACHED();
81    return 0;
82}
83
84int SVGInlineTextBox::offsetForPositionInFragment(const SVGTextFragment& fragment, float position, bool includePartialGlyphs) const
85{
86    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
87    ASSERT(textRenderer);
88
89    float scalingFactor = textRenderer->scalingFactor();
90    ASSERT(scalingFactor);
91
92    RenderStyle* style = textRenderer->style();
93    ASSERT(style);
94
95    TextRun textRun = constructTextRun(style, fragment);
96
97    // Eventually handle lengthAdjust="spacingAndGlyphs".
98    // FIXME: Handle vertical text.
99    AffineTransform fragmentTransform;
100    fragment.buildFragmentTransform(fragmentTransform);
101    if (!fragmentTransform.isIdentity())
102        textRun.setHorizontalGlyphStretch(narrowPrecisionToFloat(fragmentTransform.xScale()));
103
104    return fragment.characterOffset - start() + textRenderer->scaledFont().offsetForPosition(textRun, position * scalingFactor, includePartialGlyphs);
105}
106
107float SVGInlineTextBox::positionForOffset(int) const
108{
109    // SVG doesn't use the offset <-> position selection system.
110    ASSERT_NOT_REACHED();
111    return 0;
112}
113
114FloatRect SVGInlineTextBox::selectionRectForTextFragment(const SVGTextFragment& fragment, int startPosition, int endPosition, RenderStyle* style)
115{
116    ASSERT(startPosition < endPosition);
117    ASSERT(style);
118
119    FontCachePurgePreventer fontCachePurgePreventer;
120
121    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
122    ASSERT(textRenderer);
123
124    float scalingFactor = textRenderer->scalingFactor();
125    ASSERT(scalingFactor);
126
127    const Font& scaledFont = textRenderer->scaledFont();
128    const FontMetrics& scaledFontMetrics = scaledFont.fontMetrics();
129    FloatPoint textOrigin(fragment.x, fragment.y);
130    if (scalingFactor != 1)
131        textOrigin.scale(scalingFactor, scalingFactor);
132
133    textOrigin.move(0, -scaledFontMetrics.floatAscent());
134
135    FloatRect selectionRect = scaledFont.selectionRectForText(constructTextRun(style, fragment), textOrigin, fragment.height * scalingFactor, startPosition, endPosition);
136    if (scalingFactor == 1)
137        return selectionRect;
138
139    selectionRect.scale(1 / scalingFactor);
140    return selectionRect;
141}
142
143LayoutRect SVGInlineTextBox::localSelectionRect(int startPosition, int endPosition)
144{
145    int boxStart = start();
146    startPosition = max(startPosition - boxStart, 0);
147    endPosition = min(endPosition - boxStart, static_cast<int>(len()));
148    if (startPosition >= endPosition)
149        return LayoutRect();
150
151    RenderText* text = textRenderer();
152    ASSERT(text);
153
154    RenderStyle* style = text->style();
155    ASSERT(style);
156
157    AffineTransform fragmentTransform;
158    FloatRect selectionRect;
159    int fragmentStartPosition = 0;
160    int fragmentEndPosition = 0;
161
162    unsigned textFragmentsSize = m_textFragments.size();
163    for (unsigned i = 0; i < textFragmentsSize; ++i) {
164        const SVGTextFragment& fragment = m_textFragments.at(i);
165
166        fragmentStartPosition = startPosition;
167        fragmentEndPosition = endPosition;
168        if (!mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
169            continue;
170
171        FloatRect fragmentRect = selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style);
172        fragment.buildFragmentTransform(fragmentTransform);
173        if (!fragmentTransform.isIdentity())
174            fragmentRect = fragmentTransform.mapRect(fragmentRect);
175
176        selectionRect.unite(fragmentRect);
177    }
178
179    return enclosingIntRect(selectionRect);
180}
181
182static inline bool textShouldBePainted(RenderSVGInlineText* textRenderer)
183{
184    // Font::pixelSize(), returns FontDescription::computedPixelSize(), which returns "int(x + 0.5)".
185    // If the absolute font size on screen is below x=0.5, don't render anything.
186    return textRenderer->scaledFont().pixelSize();
187}
188
189void SVGInlineTextBox::paintSelectionBackground(PaintInfo& paintInfo)
190{
191    ASSERT(paintInfo.shouldPaintWithinRoot(renderer()));
192    ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
193    ASSERT(truncation() == cNoTruncation);
194
195    if (renderer()->style()->visibility() != VISIBLE)
196        return;
197
198    RenderObject* parentRenderer = parent()->renderer();
199    ASSERT(parentRenderer);
200    ASSERT(!parentRenderer->document()->printing());
201
202    // Determine whether or not we're selected.
203    bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
204    bool hasSelection = selectionState() != RenderObject::SelectionNone;
205    if (!hasSelection || paintSelectedTextOnly)
206        return;
207
208    Color backgroundColor = renderer()->selectionBackgroundColor();
209    if (!backgroundColor.alpha())
210        return;
211
212    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
213    ASSERT(textRenderer);
214    if (!textShouldBePainted(textRenderer))
215        return;
216
217    RenderStyle* style = parentRenderer->style();
218    ASSERT(style);
219
220    RenderStyle* selectionStyle = style;
221    if (hasSelection) {
222        selectionStyle = parentRenderer->getCachedPseudoStyle(SELECTION);
223        if (!selectionStyle)
224            selectionStyle = style;
225    }
226
227    int startPosition, endPosition;
228    selectionStartEnd(startPosition, endPosition);
229
230    int fragmentStartPosition = 0;
231    int fragmentEndPosition = 0;
232    AffineTransform fragmentTransform;
233    unsigned textFragmentsSize = m_textFragments.size();
234    for (unsigned i = 0; i < textFragmentsSize; ++i) {
235        SVGTextFragment& fragment = m_textFragments.at(i);
236        ASSERT(!m_paintingResource);
237
238        fragmentStartPosition = startPosition;
239        fragmentEndPosition = endPosition;
240        if (!mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
241            continue;
242
243        GraphicsContextStateSaver stateSaver(*paintInfo.context);
244        fragment.buildFragmentTransform(fragmentTransform);
245        if (!fragmentTransform.isIdentity())
246            paintInfo.context->concatCTM(fragmentTransform);
247
248        paintInfo.context->setFillColor(backgroundColor);
249        paintInfo.context->fillRect(selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style), backgroundColor);
250
251        m_paintingResourceMode = ApplyToDefaultMode;
252    }
253
254    ASSERT(!m_paintingResource);
255}
256
257void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUnit, LayoutUnit)
258{
259    ASSERT(paintInfo.shouldPaintWithinRoot(renderer()));
260    ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
261    ASSERT(truncation() == cNoTruncation);
262
263    if (renderer()->style()->visibility() != VISIBLE)
264        return;
265
266    // Note: We're explicitely not supporting composition & custom underlines and custom highlighters - unlike InlineTextBox.
267    // If we ever need that for SVG, it's very easy to refactor and reuse the code.
268
269    RenderObject* parentRenderer = parent()->renderer();
270    ASSERT(parentRenderer);
271
272    bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
273    bool hasSelection = !parentRenderer->document()->printing() && selectionState() != RenderObject::SelectionNone;
274    if (!hasSelection && paintSelectedTextOnly)
275        return;
276
277    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
278    ASSERT(textRenderer);
279    if (!textShouldBePainted(textRenderer))
280        return;
281
282    RenderStyle* style = parentRenderer->style();
283    ASSERT(style);
284
285    const SVGRenderStyle* svgStyle = style->svgStyle();
286    ASSERT(svgStyle);
287
288    bool hasFill = svgStyle->hasFill();
289    bool hasVisibleStroke = svgStyle->hasVisibleStroke();
290
291    RenderStyle* selectionStyle = style;
292    if (hasSelection) {
293        selectionStyle = parentRenderer->getCachedPseudoStyle(SELECTION);
294        if (selectionStyle) {
295            const SVGRenderStyle* svgSelectionStyle = selectionStyle->svgStyle();
296            ASSERT(svgSelectionStyle);
297
298            if (!hasFill)
299                hasFill = svgSelectionStyle->hasFill();
300            if (!hasVisibleStroke)
301                hasVisibleStroke = svgSelectionStyle->hasVisibleStroke();
302        } else
303            selectionStyle = style;
304    }
305
306    if (textRenderer->frame() && textRenderer->frame()->view() && textRenderer->frame()->view()->paintBehavior() & PaintBehaviorRenderingSVGMask) {
307        hasFill = true;
308        hasVisibleStroke = false;
309    }
310
311    AffineTransform fragmentTransform;
312    unsigned textFragmentsSize = m_textFragments.size();
313    for (unsigned i = 0; i < textFragmentsSize; ++i) {
314        SVGTextFragment& fragment = m_textFragments.at(i);
315        ASSERT(!m_paintingResource);
316
317        GraphicsContextStateSaver stateSaver(*paintInfo.context);
318        fragment.buildFragmentTransform(fragmentTransform);
319        if (!fragmentTransform.isIdentity())
320            paintInfo.context->concatCTM(fragmentTransform);
321
322        // Spec: All text decorations except line-through should be drawn before the text is filled and stroked; thus, the text is rendered on top of these decorations.
323        int decorations = style->textDecorationsInEffect();
324        if (decorations & TextDecorationUnderline)
325            paintDecoration(paintInfo.context, TextDecorationUnderline, fragment);
326        if (decorations & TextDecorationOverline)
327            paintDecoration(paintInfo.context, TextDecorationOverline, fragment);
328
329        // Fill text
330        if (hasFill) {
331            m_paintingResourceMode = ApplyToFillMode | ApplyToTextMode;
332            paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
333        }
334
335        // Stroke text
336        if (hasVisibleStroke) {
337            m_paintingResourceMode = ApplyToStrokeMode | ApplyToTextMode;
338            paintText(paintInfo.context, style, selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
339        }
340
341        // Spec: Line-through should be drawn after the text is filled and stroked; thus, the line-through is rendered on top of the text.
342        if (decorations & TextDecorationLineThrough)
343            paintDecoration(paintInfo.context, TextDecorationLineThrough, fragment);
344
345        m_paintingResourceMode = ApplyToDefaultMode;
346    }
347
348    ASSERT(!m_paintingResource);
349}
350
351bool SVGInlineTextBox::acquirePaintingResource(GraphicsContext*& context, float scalingFactor, RenderObject* renderer, RenderStyle* style)
352{
353    ASSERT(scalingFactor);
354    ASSERT(renderer);
355    ASSERT(style);
356    ASSERT(m_paintingResourceMode != ApplyToDefaultMode);
357
358    StyleColor fallbackColor;
359    if (m_paintingResourceMode & ApplyToFillMode)
360        m_paintingResource = RenderSVGResource::fillPaintingResource(renderer, style, fallbackColor);
361    else if (m_paintingResourceMode & ApplyToStrokeMode)
362        m_paintingResource = RenderSVGResource::strokePaintingResource(renderer, style, fallbackColor);
363    else {
364        // We're either called for stroking or filling.
365        ASSERT_NOT_REACHED();
366    }
367
368    if (!m_paintingResource)
369        return false;
370
371    if (!m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode)) {
372        if (fallbackColor.isValid()) {
373            RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
374            fallbackResource->setColor(fallbackColor.color());
375
376            m_paintingResource = fallbackResource;
377            m_paintingResource->applyResource(renderer, style, context, m_paintingResourceMode);
378        }
379    }
380
381    if (scalingFactor != 1 && m_paintingResourceMode & ApplyToStrokeMode)
382        context->setStrokeThickness(context->strokeThickness() * scalingFactor);
383
384    return true;
385}
386
387void SVGInlineTextBox::releasePaintingResource(GraphicsContext*& context, const Path* path)
388{
389    ASSERT(m_paintingResource);
390
391    RenderObject* parentRenderer = parent()->renderer();
392    ASSERT(parentRenderer);
393
394    m_paintingResource->postApplyResource(parentRenderer, context, m_paintingResourceMode, path, /*RenderSVGShape*/ 0);
395    m_paintingResource = 0;
396}
397
398bool SVGInlineTextBox::prepareGraphicsContextForTextPainting(GraphicsContext*& context, float scalingFactor, TextRun& textRun, RenderStyle* style)
399{
400    bool acquiredResource = acquirePaintingResource(context, scalingFactor, parent()->renderer(), style);
401    if (!acquiredResource)
402        return false;
403
404#if ENABLE(SVG_FONTS)
405    // SVG Fonts need access to the painting resource used to draw the current text chunk.
406    TextRun::RenderingContext* renderingContext = textRun.renderingContext();
407    if (renderingContext)
408        static_cast<SVGTextRunRenderingContext*>(renderingContext)->setActivePaintingResource(m_paintingResource);
409#endif
410
411    return true;
412}
413
414void SVGInlineTextBox::restoreGraphicsContextAfterTextPainting(GraphicsContext*& context, TextRun& textRun)
415{
416    releasePaintingResource(context, /* path */0);
417
418#if ENABLE(SVG_FONTS)
419    TextRun::RenderingContext* renderingContext = textRun.renderingContext();
420    if (renderingContext)
421        static_cast<SVGTextRunRenderingContext*>(renderingContext)->setActivePaintingResource(0);
422#else
423    UNUSED_PARAM(textRun);
424#endif
425}
426
427TextRun SVGInlineTextBox::constructTextRun(RenderStyle* style, const SVGTextFragment& fragment) const
428{
429    ASSERT(style);
430    ASSERT(textRenderer());
431
432    RenderText* text = textRenderer();
433    ASSERT(text);
434
435    // FIXME(crbug.com/264211): This should not be necessary but can occur if we
436    //                          layout during layout. Remove this when 264211 is fixed.
437    RELEASE_ASSERT(!text->needsLayout());
438
439    TextRun run(static_cast<const LChar*>(0) // characters, will be set below if non-zero.
440                , 0 // length, will be set below if non-zero.
441                , 0 // xPos, only relevant with allowTabs=true
442                , 0 // padding, only relevant for justified text, not relevant for SVG
443                , TextRun::AllowTrailingExpansion
444                , direction()
445                , dirOverride() || style->rtlOrdering() == VisualOrder /* directionalOverride */);
446
447    if (fragment.length) {
448        if (text->is8Bit())
449            run.setText(text->characters8() + fragment.characterOffset, fragment.length);
450        else
451            run.setText(text->characters16() + fragment.characterOffset, fragment.length);
452    }
453
454    if (textRunNeedsRenderingContext(style->font()))
455        run.setRenderingContext(SVGTextRunRenderingContext::create(text));
456
457    run.disableRoundingHacks();
458
459    // We handle letter & word spacing ourselves.
460    run.disableSpacing();
461
462    // Propagate the maximum length of the characters buffer to the TextRun, even when we're only processing a substring.
463    run.setCharactersLength(text->textLength() - fragment.characterOffset);
464    ASSERT(run.charactersLength() >= run.length());
465    return run;
466}
467
468bool SVGInlineTextBox::mapStartEndPositionsIntoFragmentCoordinates(const SVGTextFragment& fragment, int& startPosition, int& endPosition) const
469{
470    if (startPosition >= endPosition)
471        return false;
472
473    int offset = static_cast<int>(fragment.characterOffset) - start();
474    int length = static_cast<int>(fragment.length);
475
476    if (startPosition >= offset + length || endPosition <= offset)
477        return false;
478
479    if (startPosition < offset)
480        startPosition = 0;
481    else
482        startPosition -= offset;
483
484    if (endPosition > offset + length)
485        endPosition = length;
486    else {
487        ASSERT(endPosition >= offset);
488        endPosition -= offset;
489    }
490
491    ASSERT(startPosition < endPosition);
492    return true;
493}
494
495static inline float positionOffsetForDecoration(TextDecoration decoration, const FontMetrics& fontMetrics, float thickness)
496{
497    // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified.
498    // Compatible with Batik/Opera.
499    if (decoration == TextDecorationUnderline)
500        return fontMetrics.floatAscent() + thickness * 1.5f;
501    if (decoration == TextDecorationOverline)
502        return thickness;
503    if (decoration == TextDecorationLineThrough)
504        return fontMetrics.floatAscent() * 5 / 8.0f;
505
506    ASSERT_NOT_REACHED();
507    return 0.0f;
508}
509
510static inline float thicknessForDecoration(TextDecoration, const Font& font)
511{
512    // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified.
513    // Compatible with Batik/Opera
514    return font.size() / 20.0f;
515}
516
517static inline RenderObject* findRenderObjectDefininingTextDecoration(InlineFlowBox* parentBox)
518{
519    // Lookup first render object in parent hierarchy which has text-decoration set.
520    RenderObject* renderer = 0;
521    while (parentBox) {
522        renderer = parentBox->renderer();
523
524        if (renderer->style() && renderer->style()->textDecoration() != TextDecorationNone)
525            break;
526
527        parentBox = parentBox->parent();
528    }
529
530    ASSERT(renderer);
531    return renderer;
532}
533
534void SVGInlineTextBox::paintDecoration(GraphicsContext* context, TextDecoration decoration, const SVGTextFragment& fragment)
535{
536    if (textRenderer()->style()->textDecorationsInEffect() == TextDecorationNone)
537        return;
538
539    // Find out which render style defined the text-decoration, as its fill/stroke properties have to be used for drawing instead of ours.
540    RenderObject* decorationRenderer = findRenderObjectDefininingTextDecoration(parent());
541    RenderStyle* decorationStyle = decorationRenderer->style();
542    ASSERT(decorationStyle);
543
544    if (decorationStyle->visibility() == HIDDEN)
545        return;
546
547    const SVGRenderStyle* svgDecorationStyle = decorationStyle->svgStyle();
548    ASSERT(svgDecorationStyle);
549
550    bool hasDecorationFill = svgDecorationStyle->hasFill();
551    bool hasVisibleDecorationStroke = svgDecorationStyle->hasVisibleStroke();
552
553    if (hasDecorationFill) {
554        m_paintingResourceMode = ApplyToFillMode;
555        paintDecorationWithStyle(context, decoration, fragment, decorationRenderer);
556    }
557
558    if (hasVisibleDecorationStroke) {
559        m_paintingResourceMode = ApplyToStrokeMode;
560        paintDecorationWithStyle(context, decoration, fragment, decorationRenderer);
561    }
562}
563
564void SVGInlineTextBox::paintDecorationWithStyle(GraphicsContext* context, TextDecoration decoration, const SVGTextFragment& fragment, RenderObject* decorationRenderer)
565{
566    ASSERT(!m_paintingResource);
567    ASSERT(m_paintingResourceMode != ApplyToDefaultMode);
568
569    RenderStyle* decorationStyle = decorationRenderer->style();
570    ASSERT(decorationStyle);
571
572    float scalingFactor = 1;
573    Font scaledFont;
574    RenderSVGInlineText::computeNewScaledFontForStyle(decorationRenderer, decorationStyle, scalingFactor, scaledFont);
575    ASSERT(scalingFactor);
576
577    // The initial y value refers to overline position.
578    float thickness = thicknessForDecoration(decoration, scaledFont);
579
580    if (fragment.width <= 0 && thickness <= 0)
581        return;
582
583    FloatPoint decorationOrigin(fragment.x, fragment.y);
584    float width = fragment.width;
585    const FontMetrics& scaledFontMetrics = scaledFont.fontMetrics();
586
587    GraphicsContextStateSaver stateSaver(*context);
588    if (scalingFactor != 1) {
589        width *= scalingFactor;
590        decorationOrigin.scale(scalingFactor, scalingFactor);
591        context->scale(FloatSize(1 / scalingFactor, 1 / scalingFactor));
592    }
593
594    decorationOrigin.move(0, -scaledFontMetrics.floatAscent() + positionOffsetForDecoration(decoration, scaledFontMetrics, thickness));
595
596    Path path;
597    path.addRect(FloatRect(decorationOrigin, FloatSize(width, thickness)));
598
599    if (acquirePaintingResource(context, scalingFactor, decorationRenderer, decorationStyle))
600        releasePaintingResource(context, &path);
601}
602
603void SVGInlineTextBox::paintTextWithShadows(GraphicsContext* context, RenderStyle* style, TextRun& textRun, const SVGTextFragment& fragment, int startPosition, int endPosition)
604{
605    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
606    ASSERT(textRenderer);
607
608    float scalingFactor = textRenderer->scalingFactor();
609    ASSERT(scalingFactor);
610
611    const Font& scaledFont = textRenderer->scaledFont();
612    const ShadowData* shadow = style->textShadow();
613
614    // Text shadows are disabled when printing. http://crbug.com/258321
615    bool hasShadow = shadow && !context->printing();
616
617    FloatPoint textOrigin(fragment.x, fragment.y);
618    FloatSize textSize(fragment.width, fragment.height);
619
620    if (scalingFactor != 1) {
621        textOrigin.scale(scalingFactor, scalingFactor);
622        textSize.scale(scalingFactor);
623        context->save();
624        context->scale(FloatSize(1 / scalingFactor, 1 / scalingFactor));
625    }
626
627    if (hasShadow) {
628        DrawLooper drawLooper;
629        do {
630            FloatSize offset(shadow->x(), shadow->y());
631            drawLooper.addShadow(offset, shadow->blur(), textRenderer->resolveColor(shadow->color(), Color::stdShadowColor),
632                DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowRespectsAlpha);
633        } while ((shadow = shadow->next()));
634        drawLooper.addUnmodifiedContent();
635        context->setDrawLooper(drawLooper);
636    }
637
638    if (prepareGraphicsContextForTextPainting(context, scalingFactor, textRun, style)) {
639        TextRunPaintInfo textRunPaintInfo(textRun);
640        textRunPaintInfo.from = startPosition;
641        textRunPaintInfo.to = endPosition;
642        textRunPaintInfo.bounds = FloatRect(textOrigin, textSize);
643        scaledFont.drawText(context, textRunPaintInfo, textOrigin);
644        restoreGraphicsContextAfterTextPainting(context, textRun);
645    }
646
647    if (scalingFactor != 1)
648        context->restore();
649    else if (hasShadow)
650        context->clearShadow();
651}
652
653void SVGInlineTextBox::paintText(GraphicsContext* context, RenderStyle* style, RenderStyle* selectionStyle, const SVGTextFragment& fragment, bool hasSelection, bool paintSelectedTextOnly)
654{
655    ASSERT(style);
656    ASSERT(selectionStyle);
657
658    int startPosition = 0;
659    int endPosition = 0;
660    if (hasSelection) {
661        selectionStartEnd(startPosition, endPosition);
662        hasSelection = mapStartEndPositionsIntoFragmentCoordinates(fragment, startPosition, endPosition);
663    }
664
665    // Fast path if there is no selection, just draw the whole chunk part using the regular style
666    TextRun textRun = constructTextRun(style, fragment);
667    if (!hasSelection || startPosition >= endPosition) {
668        paintTextWithShadows(context, style, textRun, fragment, 0, fragment.length);
669        return;
670    }
671
672    // Eventually draw text using regular style until the start position of the selection
673    if (startPosition > 0 && !paintSelectedTextOnly)
674        paintTextWithShadows(context, style, textRun, fragment, 0, startPosition);
675
676    // Draw text using selection style from the start to the end position of the selection
677    if (style != selectionStyle)
678        SVGResourcesCache::clientStyleChanged(parent()->renderer(), StyleDifferenceRepaint, selectionStyle);
679
680    TextRun selectionTextRun = constructTextRun(selectionStyle, fragment);
681    paintTextWithShadows(context, selectionStyle, textRun, fragment, startPosition, endPosition);
682
683    if (style != selectionStyle)
684        SVGResourcesCache::clientStyleChanged(parent()->renderer(), StyleDifferenceRepaint, style);
685
686    // Eventually draw text using regular style from the end position of the selection to the end of the current chunk part
687    if (endPosition < static_cast<int>(fragment.length) && !paintSelectedTextOnly)
688        paintTextWithShadows(context, style, textRun, fragment, endPosition, fragment.length);
689}
690
691FloatRect SVGInlineTextBox::calculateBoundaries() const
692{
693    FloatRect textRect;
694
695    RenderSVGInlineText* textRenderer = toRenderSVGInlineText(this->textRenderer());
696    ASSERT(textRenderer);
697
698    float scalingFactor = textRenderer->scalingFactor();
699    ASSERT(scalingFactor);
700
701    float baseline = textRenderer->scaledFont().fontMetrics().floatAscent() / scalingFactor;
702
703    AffineTransform fragmentTransform;
704    unsigned textFragmentsSize = m_textFragments.size();
705    for (unsigned i = 0; i < textFragmentsSize; ++i) {
706        const SVGTextFragment& fragment = m_textFragments.at(i);
707        FloatRect fragmentRect(fragment.x, fragment.y - baseline, fragment.width, fragment.height);
708        fragment.buildFragmentTransform(fragmentTransform);
709        if (!fragmentTransform.isIdentity())
710            fragmentRect = fragmentTransform.mapRect(fragmentRect);
711
712        textRect.unite(fragmentRect);
713    }
714
715    return textRect;
716}
717
718bool SVGInlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit, LayoutUnit)
719{
720    // FIXME: integrate with InlineTextBox::nodeAtPoint better.
721    ASSERT(!isLineBreak());
722
723    PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_TEXT_HITTESTING, request, renderer()->style()->pointerEvents());
724    bool isVisible = renderer()->style()->visibility() == VISIBLE;
725    if (isVisible || !hitRules.requireVisible) {
726        if ((hitRules.canHitStroke && (renderer()->style()->svgStyle()->hasStroke() || !hitRules.requireStroke))
727            || (hitRules.canHitFill && (renderer()->style()->svgStyle()->hasFill() || !hitRules.requireFill))) {
728            FloatPoint boxOrigin(x(), y());
729            boxOrigin.moveBy(accumulatedOffset);
730            FloatRect rect(boxOrigin, size());
731            if (locationInContainer.intersects(rect)) {
732                renderer()->updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset));
733                if (!result.addNodeToRectBasedTestResult(renderer()->node(), request, locationInContainer, rect))
734                    return true;
735             }
736        }
737    }
738    return false;
739}
740
741} // namespace WebCore
742