3805c8a2c38bc3c33fd2b4c629c764e85c35472b
[WebKit-https.git] / Source / WebCore / rendering / svg / SVGInlineTextBox.cpp
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 "SVGInlineTextBox.h"
24
25 #include "Frame.h"
26 #include "FrameView.h"
27 #include "GraphicsContext.h"
28 #include "HitTestResult.h"
29 #include "InlineFlowBox.h"
30 #include "PointerEventsHitRules.h"
31 #include "RenderBlock.h"
32 #include "RenderInline.h"
33 #include "RenderSVGResourceSolidColor.h"
34 #include "RenderView.h"
35 #include "SVGRenderingContext.h"
36 #include "SVGResourcesCache.h"
37 #include "SVGRootInlineBox.h"
38 #include "TextPainter.h"
39 #include <wtf/IsoMallocInlines.h>
40
41 namespace WebCore {
42
43 WTF_MAKE_ISO_ALLOCATED_IMPL(SVGInlineTextBox);
44
45 struct ExpectedSVGInlineTextBoxSize : public InlineTextBox {
46     float float1;
47     uint32_t bitfields : 5;
48     void* pointer;
49     Vector<SVGTextFragment> vector;
50 };
51
52 COMPILE_ASSERT(sizeof(SVGInlineTextBox) == sizeof(ExpectedSVGInlineTextBoxSize), SVGInlineTextBox_is_not_of_expected_size);
53
54 SVGInlineTextBox::SVGInlineTextBox(RenderSVGInlineText& renderer)
55     : InlineTextBox(renderer)
56     , m_paintingResourceMode(OptionSet<RenderSVGResourceMode>(RenderSVGResourceMode::ApplyToDefault).toRaw())
57     , m_startsNewTextChunk(false)
58 {
59 }
60
61 void SVGInlineTextBox::dirtyOwnLineBoxes()
62 {
63     InlineTextBox::dirtyLineBoxes();
64
65     // Clear the now stale text fragments
66     clearTextFragments();
67 }
68
69 void SVGInlineTextBox::dirtyLineBoxes()
70 {
71     dirtyOwnLineBoxes();
72
73     // And clear any following text fragments as the text on which they
74     // depend may now no longer exist, or glyph positions may be wrong
75     for (InlineTextBox* nextBox = nextTextBox(); nextBox; nextBox = nextBox->nextTextBox())
76         nextBox->dirtyOwnLineBoxes();
77 }
78
79 int SVGInlineTextBox::offsetForPosition(float, bool) const
80 {
81     // SVG doesn't use the standard offset <-> position selection system, as it's not suitable for SVGs complex needs.
82     // vertical text selection, inline boxes spanning multiple lines (contrary to HTML, etc.)
83     ASSERT_NOT_REACHED();
84     return 0;
85 }
86
87 int SVGInlineTextBox::offsetForPositionInFragment(const SVGTextFragment& fragment, float position, bool includePartialGlyphs) const
88 {
89    float scalingFactor = renderer().scalingFactor();
90     ASSERT(scalingFactor);
91
92     TextRun textRun = constructTextRun(renderer().style(), fragment);
93
94     // Eventually handle lengthAdjust="spacingAndGlyphs".
95     // FIXME: Handle vertical text.
96     AffineTransform fragmentTransform;
97     fragment.buildFragmentTransform(fragmentTransform);
98     if (!fragmentTransform.isIdentity())
99         textRun.setHorizontalGlyphStretch(narrowPrecisionToFloat(fragmentTransform.xScale()));
100
101     return fragment.characterOffset - start() + renderer().scaledFont().offsetForPosition(textRun, position * scalingFactor, includePartialGlyphs);
102 }
103
104 float SVGInlineTextBox::positionForOffset(unsigned) const
105 {
106     // SVG doesn't use the offset <-> position selection system. 
107     ASSERT_NOT_REACHED();
108     return 0;
109 }
110
111 FloatRect SVGInlineTextBox::selectionRectForTextFragment(const SVGTextFragment& fragment, unsigned startPosition, unsigned endPosition, const RenderStyle& style) const
112 {
113     ASSERT_WITH_SECURITY_IMPLICATION(startPosition < endPosition);
114
115     float scalingFactor = renderer().scalingFactor();
116     ASSERT(scalingFactor);
117
118     const FontCascade& scaledFont = renderer().scaledFont();
119     const FontMetrics& scaledFontMetrics = scaledFont.fontMetrics();
120     FloatPoint textOrigin(fragment.x, fragment.y);
121     if (scalingFactor != 1)
122         textOrigin.scale(scalingFactor);
123
124     textOrigin.move(0, -scaledFontMetrics.floatAscent());
125
126     LayoutRect selectionRect = LayoutRect(textOrigin, LayoutSize(0, fragment.height * scalingFactor));
127     TextRun run = constructTextRun(style, fragment);
128     scaledFont.adjustSelectionRectForText(run, selectionRect, startPosition, endPosition);
129     FloatRect snappedSelectionRect = snapRectToDevicePixelsWithWritingDirection(selectionRect, renderer().document().deviceScaleFactor(), run.ltr());
130     if (scalingFactor == 1)
131         return snappedSelectionRect;
132
133     snappedSelectionRect.scale(1 / scalingFactor);
134     return snappedSelectionRect;
135 }
136
137 LayoutRect SVGInlineTextBox::localSelectionRect(unsigned startPosition, unsigned endPosition) const
138 {
139     startPosition = clampedOffset(startPosition);
140     endPosition = clampedOffset(endPosition);
141     if (startPosition >= endPosition)
142         return LayoutRect();
143
144     auto& style = renderer().style();
145
146     AffineTransform fragmentTransform;
147     FloatRect selectionRect;
148     unsigned fragmentStartPosition = 0;
149     unsigned fragmentEndPosition = 0;
150
151     unsigned textFragmentsSize = m_textFragments.size();
152     for (unsigned i = 0; i < textFragmentsSize; ++i) {
153         const SVGTextFragment& fragment = m_textFragments.at(i);
154
155         fragmentStartPosition = startPosition;
156         fragmentEndPosition = endPosition;
157         if (!mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
158             continue;
159
160         FloatRect fragmentRect = selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style);
161         fragment.buildFragmentTransform(fragmentTransform);
162         if (!fragmentTransform.isIdentity())
163             fragmentRect = fragmentTransform.mapRect(fragmentRect);
164
165         selectionRect.unite(fragmentRect);
166     }
167
168     return enclosingIntRect(selectionRect);
169 }
170
171 static inline bool textShouldBePainted(const RenderSVGInlineText& textRenderer)
172 {
173     // FontCascade::pixelSize(), returns FontDescription::computedPixelSize(), which returns "int(x + 0.5)".
174     // If the absolute font size on screen is below x=0.5, don't render anything.
175     return textRenderer.scaledFont().pixelSize();
176 }
177
178 void SVGInlineTextBox::paintSelectionBackground(PaintInfo& paintInfo)
179 {
180     ASSERT(paintInfo.shouldPaintWithinRoot(renderer()));
181     ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
182     ASSERT(truncation() == cNoTruncation);
183
184     if (renderer().style().visibility() != Visibility::Visible)
185         return;
186
187     auto& parentRenderer = parent()->renderer();
188     ASSERT(!parentRenderer.document().printing());
189
190     // Determine whether or not we're selected.
191     bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
192     bool hasSelection = selectionState() != RenderObject::SelectionNone;
193     if (!hasSelection || paintSelectedTextOnly)
194         return;
195
196     Color backgroundColor = renderer().selectionBackgroundColor();
197     if (!backgroundColor.isVisible())
198         return;
199
200     if (!textShouldBePainted(renderer()))
201         return;
202
203     auto& style = parentRenderer.style();
204
205     unsigned startPosition;
206     unsigned endPosition;
207     std::tie(startPosition, endPosition) = selectionStartEnd();
208
209     unsigned fragmentStartPosition = 0;
210     unsigned fragmentEndPosition = 0;
211     AffineTransform fragmentTransform;
212     unsigned textFragmentsSize = m_textFragments.size();
213     for (unsigned i = 0; i < textFragmentsSize; ++i) {
214         SVGTextFragment& fragment = m_textFragments.at(i);
215         ASSERT(!m_paintingResource);
216
217         fragmentStartPosition = startPosition;
218         fragmentEndPosition = endPosition;
219         if (!mapStartEndPositionsIntoFragmentCoordinates(fragment, fragmentStartPosition, fragmentEndPosition))
220             continue;
221
222         GraphicsContextStateSaver stateSaver(paintInfo.context());
223         fragment.buildFragmentTransform(fragmentTransform);
224         if (!fragmentTransform.isIdentity())
225             paintInfo.context().concatCTM(fragmentTransform);
226
227         paintInfo.context().setFillColor(backgroundColor);
228         paintInfo.context().fillRect(selectionRectForTextFragment(fragment, fragmentStartPosition, fragmentEndPosition, style), backgroundColor);
229
230         setPaintingResourceMode(RenderSVGResourceMode::ApplyToDefault);
231     }
232
233     ASSERT(!m_paintingResource);
234 }
235
236 void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit, LayoutUnit)
237 {
238     ASSERT(paintInfo.shouldPaintWithinRoot(renderer()));
239     ASSERT(paintInfo.phase == PaintPhaseForeground || paintInfo.phase == PaintPhaseSelection);
240     ASSERT(truncation() == cNoTruncation);
241
242     if (renderer().style().visibility() != Visibility::Visible)
243         return;
244
245     // Note: We're explicitely not supporting composition & custom underlines and custom highlighters - unlike InlineTextBox.
246     // If we ever need that for SVG, it's very easy to refactor and reuse the code.
247
248     auto& parentRenderer = parent()->renderer();
249
250     bool paintSelectedTextOnly = paintInfo.phase == PaintPhaseSelection;
251     bool shouldPaintSelectionHighlight = !(paintInfo.paintBehavior & PaintBehaviorSkipSelectionHighlight);
252     bool hasSelection = !parentRenderer.document().printing() && selectionState() != RenderObject::SelectionNone;
253     if (!hasSelection && paintSelectedTextOnly)
254         return;
255
256     if (!textShouldBePainted(renderer()))
257         return;
258
259     auto& style = parentRenderer.style();
260
261     const SVGRenderStyle& svgStyle = style.svgStyle();
262
263     bool hasFill = svgStyle.hasFill();
264     bool hasVisibleStroke = style.hasVisibleStroke();
265
266     const RenderStyle* selectionStyle = &style;
267     if (hasSelection && shouldPaintSelectionHighlight) {
268         selectionStyle = parentRenderer.getCachedPseudoStyle(PseudoId::Selection);
269         if (selectionStyle) {
270             const SVGRenderStyle& svgSelectionStyle = selectionStyle->svgStyle();
271
272             if (!hasFill)
273                 hasFill = svgSelectionStyle.hasFill();
274             if (!hasVisibleStroke)
275                 hasVisibleStroke = selectionStyle->hasVisibleStroke();
276         } else
277             selectionStyle = &style;
278     }
279
280     if (renderer().view().frameView().paintBehavior() & PaintBehaviorRenderingSVGMask) {
281         hasFill = true;
282         hasVisibleStroke = false;
283     }
284
285     AffineTransform fragmentTransform;
286     unsigned textFragmentsSize = m_textFragments.size();
287     for (unsigned i = 0; i < textFragmentsSize; ++i) {
288         SVGTextFragment& fragment = m_textFragments.at(i);
289         ASSERT(!m_paintingResource);
290
291         GraphicsContextStateSaver stateSaver(paintInfo.context());
292         fragment.buildFragmentTransform(fragmentTransform);
293         if (!fragmentTransform.isIdentity())
294             paintInfo.context().concatCTM(fragmentTransform);
295
296         // 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.
297         auto decorations = style.textDecorationsInEffect();
298         if (decorations & TextDecoration::Underline)
299             paintDecoration(paintInfo.context(), TextDecoration::Underline, fragment);
300         if (decorations & TextDecoration::Overline)
301             paintDecoration(paintInfo.context(), TextDecoration::Overline, fragment);
302
303         auto paintOrder = RenderStyle::paintTypesForPaintOrder(style.paintOrder());
304         for (unsigned i = 0; i < paintOrder.size(); ++i) {
305             switch (paintOrder.at(i)) {
306             case PaintType::Fill:
307                 if (!hasFill)
308                     continue;
309                 setPaintingResourceMode({ RenderSVGResourceMode::ApplyToFill, RenderSVGResourceMode::ApplyToText });
310                 ASSERT(selectionStyle);
311                 paintText(paintInfo.context(), style, *selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
312                 break;
313             case PaintType::Stroke:
314                 if (!hasVisibleStroke)
315                     continue;
316                 setPaintingResourceMode({ RenderSVGResourceMode::ApplyToStroke, RenderSVGResourceMode::ApplyToText});
317                 ASSERT(selectionStyle);
318                 paintText(paintInfo.context(), style, *selectionStyle, fragment, hasSelection, paintSelectedTextOnly);
319                 break;
320             case PaintType::Markers:
321                 continue;
322             }
323         }
324
325         // Spec: Line-through should be drawn after the text is filled and stroked; thus, the line-through is rendered on top of the text.
326         if (decorations & TextDecoration::LineThrough)
327             paintDecoration(paintInfo.context(), TextDecoration::LineThrough, fragment);
328
329         setPaintingResourceMode(RenderSVGResourceMode::ApplyToDefault);
330     }
331
332     // Finally, paint the outline if any.
333     if (renderer().style().hasOutline() && is<RenderInline>(parentRenderer))
334         downcast<RenderInline>(parentRenderer).paintOutline(paintInfo, paintOffset);
335
336     ASSERT(!m_paintingResource);
337 }
338
339 bool SVGInlineTextBox::acquirePaintingResource(GraphicsContext*& context, float scalingFactor, RenderBoxModelObject& renderer, const RenderStyle& style)
340 {
341     ASSERT(scalingFactor);
342     ASSERT(paintingResourceMode() != RenderSVGResourceMode::ApplyToDefault);
343
344     Color fallbackColor;
345     if (paintingResourceMode().contains(RenderSVGResourceMode::ApplyToFill))
346         m_paintingResource = RenderSVGResource::fillPaintingResource(renderer, style, fallbackColor);
347     else if (paintingResourceMode().contains(RenderSVGResourceMode::ApplyToStroke))
348         m_paintingResource = RenderSVGResource::strokePaintingResource(renderer, style, fallbackColor);
349     else {
350         // We're either called for stroking or filling.
351         ASSERT_NOT_REACHED();
352     }
353
354     if (!m_paintingResource)
355         return false;
356
357     if (!m_paintingResource->applyResource(renderer, style, context, paintingResourceMode())) {
358         if (fallbackColor.isValid()) {
359             RenderSVGResourceSolidColor* fallbackResource = RenderSVGResource::sharedSolidPaintingResource();
360             fallbackResource->setColor(fallbackColor);
361
362             m_paintingResource = fallbackResource;
363             m_paintingResource->applyResource(renderer, style, context, paintingResourceMode());
364         }
365     }
366
367     if (scalingFactor != 1 && paintingResourceMode().contains(RenderSVGResourceMode::ApplyToStroke))
368         context->setStrokeThickness(context->strokeThickness() * scalingFactor);
369
370     return true;
371 }
372
373 void SVGInlineTextBox::releasePaintingResource(GraphicsContext*& context, const Path* path)
374 {
375     ASSERT(m_paintingResource);
376
377     m_paintingResource->postApplyResource(parent()->renderer(), context, paintingResourceMode(), path, /*RenderSVGShape*/ nullptr);
378     m_paintingResource = nullptr;
379 }
380
381 bool SVGInlineTextBox::prepareGraphicsContextForTextPainting(GraphicsContext*& context, float scalingFactor, const RenderStyle& style)
382 {
383     return acquirePaintingResource(context, scalingFactor, parent()->renderer(), style);
384 }
385
386 void SVGInlineTextBox::restoreGraphicsContextAfterTextPainting(GraphicsContext*& context)
387 {
388     releasePaintingResource(context, /* path */nullptr);
389 }
390
391 TextRun SVGInlineTextBox::constructTextRun(const RenderStyle& style, const SVGTextFragment& fragment) const
392 {
393     TextRun run(StringView(renderer().text()).substring(fragment.characterOffset, fragment.length)
394                 , 0 /* xPos, only relevant with allowTabs=true */
395                 , 0 /* padding, only relevant for justified text, not relevant for SVG */
396                 , AllowTrailingExpansion
397                 , direction()
398                 , dirOverride() || style.rtlOrdering() == Order::Visual /* directionalOverride */);
399
400     // We handle letter & word spacing ourselves.
401     run.disableSpacing();
402     return run;
403 }
404
405 bool SVGInlineTextBox::mapStartEndPositionsIntoFragmentCoordinates(const SVGTextFragment& fragment, unsigned& startPosition, unsigned& endPosition) const
406 {
407     if (startPosition >= endPosition)
408         return false;
409
410     ASSERT(fragment.characterOffset >= start());
411     unsigned offset = fragment.characterOffset - start();
412     unsigned length = fragment.length;
413
414     if (startPosition >= offset + length || endPosition <= offset)
415         return false;
416
417     if (startPosition < offset)
418         startPosition = 0;
419     else {
420         ASSERT(startPosition >= offset);
421         startPosition -= offset;
422     }
423
424     if (endPosition > offset + length)
425         endPosition = length;
426     else {
427         ASSERT(endPosition >= offset);
428         endPosition -= offset;
429     }
430
431     ASSERT_WITH_SECURITY_IMPLICATION(startPosition < endPosition);
432     return true;
433 }
434
435 static inline float positionOffsetForDecoration(OptionSet<TextDecoration> decoration, const FontMetrics& fontMetrics, float thickness)
436 {
437     // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified.
438     // Compatible with Batik/Opera.
439     if (decoration == TextDecoration::Underline)
440         return fontMetrics.floatAscent() + thickness * 1.5f;
441     if (decoration == TextDecoration::Overline)
442         return thickness;
443     if (decoration == TextDecoration::LineThrough)
444         return fontMetrics.floatAscent() * 5 / 8.0f;
445
446     ASSERT_NOT_REACHED();
447     return 0.0f;
448 }
449
450 static inline float thicknessForDecoration(OptionSet<TextDecoration>, const FontCascade& font)
451 {
452     // FIXME: For SVG Fonts we need to use the attributes defined in the <font-face> if specified.
453     // Compatible with Batik/Opera
454     return font.size() / 20.0f;
455 }
456
457 static inline RenderBoxModelObject& findRendererDefininingTextDecoration(InlineFlowBox* parentBox)
458 {
459     // Lookup first render object in parent hierarchy which has text-decoration set.
460     RenderBoxModelObject* renderer = nullptr;
461     while (parentBox) {
462         renderer = &parentBox->renderer();
463
464         if (!renderer->style().textDecoration().isEmpty())
465             break;
466
467         parentBox = parentBox->parent();
468     }
469
470     ASSERT(renderer);
471     return *renderer;
472 }
473
474 void SVGInlineTextBox::paintDecoration(GraphicsContext& context, OptionSet<TextDecoration> decoration, const SVGTextFragment& fragment)
475 {
476     if (renderer().style().textDecorationsInEffect().isEmpty())
477         return;
478
479     // Find out which render style defined the text-decoration, as its fill/stroke properties have to be used for drawing instead of ours.
480     auto& decorationRenderer = findRendererDefininingTextDecoration(parent());
481     const RenderStyle& decorationStyle = decorationRenderer.style();
482
483     if (decorationStyle.visibility() == Visibility::Hidden)
484         return;
485
486     const SVGRenderStyle& svgDecorationStyle = decorationStyle.svgStyle();
487
488     bool hasDecorationFill = svgDecorationStyle.hasFill();
489     bool hasVisibleDecorationStroke = decorationStyle.hasVisibleStroke();
490
491     if (hasDecorationFill) {
492         setPaintingResourceMode(RenderSVGResourceMode::ApplyToFill);
493         paintDecorationWithStyle(context, decoration, fragment, decorationRenderer);
494     }
495
496     if (hasVisibleDecorationStroke) {
497         setPaintingResourceMode(RenderSVGResourceMode::ApplyToStroke);
498         paintDecorationWithStyle(context, decoration, fragment, decorationRenderer);
499     }
500 }
501
502 void SVGInlineTextBox::paintDecorationWithStyle(GraphicsContext& context, OptionSet<TextDecoration> decoration, const SVGTextFragment& fragment, RenderBoxModelObject& decorationRenderer)
503 {
504     ASSERT(!m_paintingResource);
505     ASSERT(paintingResourceMode() != RenderSVGResourceMode::ApplyToDefault);
506
507     auto& decorationStyle = decorationRenderer.style();
508
509     float scalingFactor = 1;
510     FontCascade scaledFont;
511     RenderSVGInlineText::computeNewScaledFontForStyle(decorationRenderer, decorationStyle, scalingFactor, scaledFont);
512     ASSERT(scalingFactor);
513
514     // The initial y value refers to overline position.
515     float thickness = thicknessForDecoration(decoration, scaledFont);
516
517     if (fragment.width <= 0 && thickness <= 0)
518         return;
519
520     FloatPoint decorationOrigin(fragment.x, fragment.y);
521     float width = fragment.width;
522     const FontMetrics& scaledFontMetrics = scaledFont.fontMetrics();
523
524     GraphicsContextStateSaver stateSaver(context);
525     if (scalingFactor != 1) {
526         width *= scalingFactor;
527         decorationOrigin.scale(scalingFactor);
528         context.scale(1 / scalingFactor);
529     }
530
531     decorationOrigin.move(0, -scaledFontMetrics.floatAscent() + positionOffsetForDecoration(decoration, scaledFontMetrics, thickness));
532
533     Path path;
534     path.addRect(FloatRect(decorationOrigin, FloatSize(width, thickness)));
535
536     GraphicsContext* contextPtr = &context;
537     if (acquirePaintingResource(contextPtr, scalingFactor, decorationRenderer, decorationStyle))
538         releasePaintingResource(contextPtr, &path);
539 }
540
541 void SVGInlineTextBox::paintTextWithShadows(GraphicsContext& context, const RenderStyle& style, TextRun& textRun, const SVGTextFragment& fragment, unsigned startPosition, unsigned endPosition)
542 {
543     float scalingFactor = renderer().scalingFactor();
544     ASSERT(scalingFactor);
545
546     const FontCascade& scaledFont = renderer().scaledFont();
547     const ShadowData* shadow = style.textShadow();
548
549     FloatPoint textOrigin(fragment.x, fragment.y);
550     FloatSize textSize(fragment.width, fragment.height);
551
552     if (scalingFactor != 1) {
553         textOrigin.scale(scalingFactor);
554         textSize.scale(scalingFactor);
555     }
556
557     FloatRect shadowRect(FloatPoint(textOrigin.x(), textOrigin.y() - scaledFont.fontMetrics().floatAscent()), textSize);
558
559     GraphicsContext* usedContext = &context;
560     do {
561         if (!prepareGraphicsContextForTextPainting(usedContext, scalingFactor, style))
562             break;
563
564         {
565             ShadowApplier shadowApplier(*usedContext, shadow, nullptr, shadowRect);
566
567             if (!shadowApplier.didSaveContext())
568                 usedContext->save();
569             usedContext->scale(1 / scalingFactor);
570
571             scaledFont.drawText(*usedContext, textRun, textOrigin + shadowApplier.extraOffset(), startPosition, endPosition);
572
573             if (!shadowApplier.didSaveContext())
574                 usedContext->restore();
575         }
576
577         restoreGraphicsContextAfterTextPainting(usedContext);
578
579         if (!shadow)
580             break;
581
582         shadow = shadow->next();
583     } while (shadow);
584 }
585
586 void SVGInlineTextBox::paintText(GraphicsContext& context, const RenderStyle& style, const RenderStyle& selectionStyle, const SVGTextFragment& fragment, bool hasSelection, bool paintSelectedTextOnly)
587 {
588     unsigned startPosition = 0;
589     unsigned endPosition = 0;
590     if (hasSelection) {
591         std::tie(startPosition, endPosition) = selectionStartEnd();
592         hasSelection = mapStartEndPositionsIntoFragmentCoordinates(fragment, startPosition, endPosition);
593     }
594
595     // Fast path if there is no selection, just draw the whole chunk part using the regular style
596     TextRun textRun = constructTextRun(style, fragment);
597     if (!hasSelection || startPosition >= endPosition) {
598         paintTextWithShadows(context, style, textRun, fragment, 0, fragment.length);
599         return;
600     }
601
602     // Eventually draw text using regular style until the start position of the selection
603     if (startPosition > 0 && !paintSelectedTextOnly)
604         paintTextWithShadows(context, style, textRun, fragment, 0, startPosition);
605
606     // Draw text using selection style from the start to the end position of the selection
607     if (style != selectionStyle)
608         SVGResourcesCache::clientStyleChanged(parent()->renderer(), StyleDifference::Repaint, selectionStyle);
609
610     paintTextWithShadows(context, selectionStyle, textRun, fragment, startPosition, endPosition);
611
612     if (style != selectionStyle)
613         SVGResourcesCache::clientStyleChanged(parent()->renderer(), StyleDifference::Repaint, style);
614
615     // Eventually draw text using regular style from the end position of the selection to the end of the current chunk part
616     if (endPosition < fragment.length && !paintSelectedTextOnly)
617         paintTextWithShadows(context, style, textRun, fragment, endPosition, fragment.length);
618 }
619
620 FloatRect SVGInlineTextBox::calculateBoundaries() const
621 {
622     FloatRect textRect;
623
624     float scalingFactor = renderer().scalingFactor();
625     ASSERT(scalingFactor);
626
627     float baseline = renderer().scaledFont().fontMetrics().floatAscent() / scalingFactor;
628
629     AffineTransform fragmentTransform;
630     unsigned textFragmentsSize = m_textFragments.size();
631     for (unsigned i = 0; i < textFragmentsSize; ++i) {
632         const SVGTextFragment& fragment = m_textFragments.at(i);
633         FloatRect fragmentRect(fragment.x, fragment.y - baseline, fragment.width, fragment.height);
634         fragment.buildFragmentTransform(fragmentTransform);
635         if (!fragmentTransform.isIdentity())
636             fragmentRect = fragmentTransform.mapRect(fragmentRect);
637
638         textRect.unite(fragmentRect);
639     }
640
641     return textRect;
642 }
643
644 bool SVGInlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit, LayoutUnit, HitTestAction)
645 {
646     // FIXME: integrate with InlineTextBox::nodeAtPoint better.
647     ASSERT(!isLineBreak());
648
649     PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_TEXT_HITTESTING, request, renderer().style().pointerEvents());
650     bool isVisible = renderer().style().visibility() == Visibility::Visible;
651     if (isVisible || !hitRules.requireVisible) {
652         if ((hitRules.canHitStroke && (renderer().style().svgStyle().hasStroke() || !hitRules.requireStroke))
653             || (hitRules.canHitFill && (renderer().style().svgStyle().hasFill() || !hitRules.requireFill))) {
654             FloatPoint boxOrigin(x(), y());
655             boxOrigin.moveBy(accumulatedOffset);
656             FloatRect rect(boxOrigin, size());
657             if (locationInContainer.intersects(rect)) {
658
659                 float scalingFactor = renderer().scalingFactor();
660                 ASSERT(scalingFactor);
661                 
662                 float baseline = renderer().scaledFont().fontMetrics().floatAscent() / scalingFactor;
663
664                 AffineTransform fragmentTransform;
665                 for (auto& fragment : m_textFragments) {
666                     FloatQuad fragmentQuad(FloatRect(fragment.x, fragment.y - baseline, fragment.width, fragment.height));
667                     fragment.buildFragmentTransform(fragmentTransform);
668                     if (!fragmentTransform.isIdentity())
669                         fragmentQuad = fragmentTransform.mapQuad(fragmentQuad);
670                     
671                     if (fragmentQuad.containsPoint(locationInContainer.point())) {
672                         renderer().updateHitTestResult(result, locationInContainer.point() - toLayoutSize(accumulatedOffset));
673                         if (result.addNodeToListBasedTestResult(&renderer().textNode(), request, locationInContainer, rect) == HitTestProgress::Stop)
674                             return true;
675                     }
676                 }
677              }
678         }
679     }
680     return false;
681 }
682
683 } // namespace WebCore