summaryrefslogtreecommitdiffstats
path: root/WebCore/rendering/SVGInlineTextBox.cpp
blob: 8bd7fef4f27fb6914fc93c328da187ffc737c8eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
/**
 * Copyright (C) 2007 Rob Buis <buis@kde.org>
 *           (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) Research In Motion Limited 2010. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "config.h"

#if ENABLE(SVG)
#include "SVGInlineTextBox.h"

#include "Frame.h"
#include "GraphicsContext.h"
#include "InlineFlowBox.h"
#include "RenderSVGResource.h"
#include "SVGRootInlineBox.h"
#include "SVGTextLayoutUtilities.h"
#include "Text.h"

#include <float.h>

namespace WebCore {

SVGInlineTextBox::SVGInlineTextBox(RenderObject* obj)
    : InlineTextBox(obj)
    , m_height(0)
{
}

SVGRootInlineBox* SVGInlineTextBox::svgRootInlineBox() const
{
    // Find associated root inline box
    InlineFlowBox* parentBox = parent();

    while (parentBox && !parentBox->isRootInlineBox())
        parentBox = parentBox->parent();

    ASSERT(parentBox);
    ASSERT(parentBox->isRootInlineBox());

    if (!parentBox->isSVGRootInlineBox())
        return 0;

    return static_cast<SVGRootInlineBox*>(parentBox);
}

float SVGInlineTextBox::calculateGlyphWidth(RenderStyle* style, int offset, int extraCharsAvailable, int& charsConsumed, String& glyphName) const
{
    ASSERT(style);
    return style->font().floatWidth(svgTextRunForInlineTextBox(textRenderer()->characters() + offset, 1, style, this, 0), extraCharsAvailable, charsConsumed, glyphName);
}

float SVGInlineTextBox::calculateGlyphHeight(RenderStyle* style, int, int) const
{
    // This is just a guess, and the only purpose of this function is to centralize this hack.
    // In real-life top-top-bottom scripts this won't be enough, I fear.
    return style->font().ascent() + style->font().descent();
}

FloatRect SVGInlineTextBox::calculateGlyphBoundaries(RenderStyle* style, int offset, const SVGChar& svgChar) const
{
    const Font& font = style->font();

    // Take RTL text into account and pick right glyph width/height.
    float glyphWidth = 0.0f;

    // FIXME: account for multi-character glyphs
    int charsConsumed;
    String glyphName;
    if (direction() == LTR)
        glyphWidth = calculateGlyphWidth(style, offset, 0, charsConsumed, glyphName);
    else
        glyphWidth = calculateGlyphWidth(style, start() + end() - offset, 0, charsConsumed, glyphName);

    float x1 = svgChar.x;
    float x2 = svgChar.x + glyphWidth;

    float y1 = svgChar.y - font.ascent();
    float y2 = svgChar.y + font.descent();

    FloatRect glyphRect(x1, y1, x2 - x1, y2 - y1);

    // Take per-character transformations into account
    glyphRect = svgChar.characterTransform().mapRect(glyphRect);

    return glyphRect;
}

// Helper class for closestCharacterToPosition()
struct SVGInlineTextBoxClosestCharacterToPositionWalker {
    SVGInlineTextBoxClosestCharacterToPositionWalker(int x, int y)
        : m_character(0)
        , m_distance(FLT_MAX)
        , m_x(x)
        , m_y(y)
        , m_offsetOfHitCharacter(0)
    {
    }

    void chunkPortionCallback(SVGInlineTextBox* textBox, int startOffset, const AffineTransform& chunkCtm,
                              const Vector<SVGChar>::iterator& start, const Vector<SVGChar>::iterator& end)
    {
        RenderStyle* style = textBox->textRenderer()->style();

        Vector<SVGChar>::iterator closestCharacter = 0;
        unsigned int closestOffset = UINT_MAX;

        for (Vector<SVGChar>::iterator it = start; it != end; ++it) {
            if (it->isHidden())
                continue;

            unsigned int newOffset = textBox->start() + (it - start) + startOffset;
            FloatRect glyphRect = chunkCtm.mapRect(textBox->calculateGlyphBoundaries(style, newOffset, *it));

            // Take RTL text into account and pick right glyph width/height.
            // NOTE: This offset has to be corrected _after_ calling calculateGlyphBoundaries
            if (textBox->direction() == RTL)
                newOffset = textBox->start() + textBox->end() - newOffset;

            // Calculate distances relative to the glyph mid-point. I hope this is accurate enough.
            float xDistance = glyphRect.x() + glyphRect.width() / 2.0f - m_x;
            float yDistance = glyphRect.y() - glyphRect.height() / 2.0f - m_y;

            float newDistance = sqrtf(xDistance * xDistance + yDistance * yDistance);
            if (newDistance <= m_distance) {
                m_distance = newDistance;
                closestOffset = newOffset;
                closestCharacter = it;
            }
        }

        if (closestOffset != UINT_MAX) {
            // Record current chunk, if it contains the current closest character next to the mouse.
            m_character = closestCharacter;
            m_offsetOfHitCharacter = closestOffset;
        }
    }

    SVGChar* character() const
    {
        return m_character;
    }

    int offsetOfHitCharacter() const
    {
        if (!m_character)
            return 0;

        return m_offsetOfHitCharacter;
    }

private:
    Vector<SVGChar>::iterator m_character;
    float m_distance;

    int m_x;
    int m_y;
    int m_offsetOfHitCharacter;
};

// Helper class for selectionRect()
struct SVGInlineTextBoxSelectionRectWalker {
    SVGInlineTextBoxSelectionRectWalker()
    {
    }

    void chunkPortionCallback(SVGInlineTextBox* textBox, int startOffset, const AffineTransform& chunkCtm,
                              const Vector<SVGChar>::iterator& start, const Vector<SVGChar>::iterator& end)
    {
        RenderStyle* style = textBox->textRenderer()->style();

        for (Vector<SVGChar>::iterator it = start; it != end; ++it) {
            if (it->isHidden())
                continue;

            unsigned int newOffset = textBox->start() + (it - start) + startOffset;
            m_selectionRect.unite(textBox->calculateGlyphBoundaries(style, newOffset, *it));
        }

        m_selectionRect = chunkCtm.mapRect(m_selectionRect);
    }

    FloatRect selectionRect() const
    {
        return m_selectionRect;
    }

private:
    FloatRect m_selectionRect;
};

SVGChar* SVGInlineTextBox::closestCharacterToPosition(int x, int y, int& offsetOfHitCharacter) const
{
    SVGRootInlineBox* rootBox = svgRootInlineBox();
    if (!rootBox)
        return 0;

    SVGInlineTextBoxClosestCharacterToPositionWalker walkerCallback(x, y);
    SVGTextChunkWalker<SVGInlineTextBoxClosestCharacterToPositionWalker> walker(&walkerCallback, &SVGInlineTextBoxClosestCharacterToPositionWalker::chunkPortionCallback);

    rootBox->walkTextChunks(&walker, this);

    offsetOfHitCharacter = walkerCallback.offsetOfHitCharacter();
    return walkerCallback.character();
}

bool SVGInlineTextBox::svgCharacterHitsPosition(int x, int y, int& closestOffsetInBox) const
{
    int offsetOfHitCharacter = 0;
    SVGChar* charAtPosPtr = closestCharacterToPosition(x, y, offsetOfHitCharacter);
    if (!charAtPosPtr)
        return false;

    SVGChar& charAtPos = *charAtPosPtr;
    RenderStyle* style = textRenderer()->style(m_firstLine);
    FloatRect glyphRect = calculateGlyphBoundaries(style, offsetOfHitCharacter, charAtPos);

    // FIXME: Why?
    if (direction() == RTL)
        offsetOfHitCharacter++;

    // The caller actually the closest offset before/after the hit char
    // closestCharacterToPosition returns us offsetOfHitCharacter.
    closestOffsetInBox = offsetOfHitCharacter;

    // FIXME: (bug 13910) This code does not handle bottom-to-top/top-to-bottom vertical text.

    // Check whether y position hits the current character 
    if (y < charAtPos.y - glyphRect.height() || y > charAtPos.y)
        return false;

    // Check whether x position hits the current character
    if (x < charAtPos.x) {
        if (closestOffsetInBox > 0 && direction() == LTR)
            return true;
        if (closestOffsetInBox < static_cast<int>(end()) && direction() == RTL)
            return true;

        return false;
    }

    // Adjust the closest offset to after the char if x was after the char midpoint
    if (x >= charAtPos.x + glyphRect.width() / 2.0)
        closestOffsetInBox += direction() == RTL ? -1 : 1;

    // If we are past the last glyph of this box, don't mark it as 'hit'
    if (x >= charAtPos.x + glyphRect.width() && closestOffsetInBox == (int) end())
        return false;

    return true;
}

int SVGInlineTextBox::offsetForPosition(int, bool) const
{
    // SVG doesn't use the offset <-> position selection system. 
    ASSERT_NOT_REACHED();
    return 0;
}

int SVGInlineTextBox::positionForOffset(int) const
{
    // SVG doesn't use the offset <-> position selection system. 
    ASSERT_NOT_REACHED();
    return 0;
}

bool SVGInlineTextBox::nodeAtPoint(const HitTestRequest&, HitTestResult& result, int x, int y, int tx, int ty)
{
    ASSERT(!isLineBreak());

    IntRect rect = selectionRect(0, 0, 0, len());
    if (renderer()->style()->visibility() == VISIBLE && rect.contains(x, y)) {
        renderer()->updateHitTestResult(result, IntPoint(x - tx, y - ty));
        return true;
    }

    return false;
}

IntRect SVGInlineTextBox::selectionRect(int, int, int startPos, int endPos)
{
    if (startPos >= endPos)
        return IntRect();

    // TODO: Actually respect startPos/endPos - we're returning the _full_ selectionRect
    // here. This won't lead to visible bugs, but to extra work being done. Investigate.
    SVGRootInlineBox* rootBox = svgRootInlineBox();
    if (!rootBox)
        return IntRect();

    SVGInlineTextBoxSelectionRectWalker walkerCallback;
    SVGTextChunkWalker<SVGInlineTextBoxSelectionRectWalker> walker(&walkerCallback, &SVGInlineTextBoxSelectionRectWalker::chunkPortionCallback);

    rootBox->walkTextChunks(&walker, this);
    return enclosingIntRect(walkerCallback.selectionRect());
}

bool SVGInlineTextBox::chunkSelectionStartEnd(const UChar* chunk, int chunkLength, int& selectionStart, int& selectionEnd)
{
    // NOTE: We ignore SVGInlineTextBox::m_start here because it is always 0.
    //       Curently SVG doesn't use HTML block-level layout, in which m_start would be set.

    int chunkStart = chunk - textRenderer()->characters();
    ASSERT(0 <= chunkStart);    

    selectionStartEnd(selectionStart, selectionEnd);
    if (selectionEnd <= chunkStart)
        return false;
    if (chunkStart + chunkLength <= selectionStart)
        return false;

    // Map indices from view-global to chunk-local.
    selectionStart -= chunkStart;
    selectionEnd -= chunkStart;
    // Then clamp with chunk range
    if (selectionStart < 0)
        selectionStart = 0;
    if (chunkLength < selectionEnd)
        selectionEnd = chunkLength;

    return selectionStart < selectionEnd;
}

void SVGInlineTextBox::paintCharacters(RenderObject::PaintInfo& paintInfo, int tx, int ty, const SVGChar& svgChar, const UChar* chars, int length, SVGTextPaintInfo& textPaintInfo)
{
    if (renderer()->style()->visibility() != VISIBLE || paintInfo.phase == PaintPhaseOutline)
        return;

    ASSERT(paintInfo.phase != PaintPhaseSelfOutline && paintInfo.phase != PaintPhaseChildOutlines);

    RenderText* text = textRenderer();
    ASSERT(text);

    bool isPrinting = text->document()->printing();

    // Determine whether or not we're selected.
    bool haveSelection = !isPrinting && selectionState() != RenderObject::SelectionNone;
    if (!haveSelection && paintInfo.phase == PaintPhaseSelection)
        // When only painting the selection, don't bother to paint if there is none.
        return;

    // Determine whether or not we have a composition.
    bool containsComposition = text->document()->frame()->editor()->compositionNode() == text->node();
    bool useCustomUnderlines = containsComposition && text->document()->frame()->editor()->compositionUsesCustomUnderlines();

    // Set our font
    RenderStyle* styleToUse = text->style(isFirstLineStyle());
    const Font& font = styleToUse->font();

    AffineTransform ctm = svgChar.characterTransform();
    if (!ctm.isIdentity())
        paintInfo.context->concatCTM(ctm);

    // 1. Paint backgrounds behind text if needed.  Examples of such backgrounds include selection
    // and marked text.
    if (paintInfo.phase != PaintPhaseSelection && !isPrinting && textPaintInfo.subphase == SVGTextPaintSubphaseBackground) {
#if PLATFORM(MAC)
        // Custom highlighters go behind everything else.
        if (styleToUse->highlight() != nullAtom && !paintInfo.context->paintingDisabled())
            paintCustomHighlight(tx, ty, styleToUse->highlight());
#endif

        if (containsComposition && !useCustomUnderlines)
            paintCompositionBackground(paintInfo.context, tx, ty, styleToUse, font, 
                                       text->document()->frame()->editor()->compositionStart(),
                                       text->document()->frame()->editor()->compositionEnd());
        
        paintDocumentMarkers(paintInfo.context, tx, ty, styleToUse, font, true);

        if (haveSelection && !useCustomUnderlines) {
            int boxStartOffset = chars - text->characters() - start();
            paintSelection(boxStartOffset, svgChar, chars, length, paintInfo.context, styleToUse, font);
        }
    }

    bool isGlyphPhase = textPaintInfo.subphase == SVGTextPaintSubphaseGlyphFill || textPaintInfo.subphase == SVGTextPaintSubphaseGlyphStroke;
    bool isSelectionGlyphPhase = textPaintInfo.subphase == SVGTextPaintSubphaseGlyphFillSelection || textPaintInfo.subphase == SVGTextPaintSubphaseGlyphStrokeSelection;

    if  (isGlyphPhase || isSelectionGlyphPhase) {
        // Set a text shadow if we have one.
        // FIXME: Support multiple shadow effects.  See how it's done in InlineTextBox.cpp.
        bool setShadow = false;
        if (styleToUse->textShadow()) {
            paintInfo.context->setShadow(IntSize(styleToUse->textShadow()->x(), styleToUse->textShadow()->y()),
                                         styleToUse->textShadow()->blur(), styleToUse->textShadow()->color(),
                                         styleToUse->colorSpace());
            setShadow = true;
        }

        IntPoint origin((int) svgChar.x, (int) svgChar.y);
        TextRun run = svgTextRunForInlineTextBox(chars, length, styleToUse, this, svgChar.x);

#if ENABLE(SVG_FONTS)
        // SVG Fonts need access to the painting resource used to draw the current text chunk.
        ASSERT(textPaintInfo.activePaintingResource);
        run.setActivePaintingResource(textPaintInfo.activePaintingResource);
#endif

        int selectionStart = 0;
        int selectionEnd = 0;
        bool haveSelectedRange = haveSelection && chunkSelectionStartEnd(chars, length, selectionStart, selectionEnd);
        
        if (isGlyphPhase) {
            if (haveSelectedRange) {
                paintInfo.context->drawText(font, run, origin, 0, selectionStart);
                paintInfo.context->drawText(font, run, origin, selectionEnd, run.length());
            } else
                paintInfo.context->drawText(font, run, origin);
        } else {
            ASSERT(isSelectionGlyphPhase);
            if (haveSelectedRange)
                paintInfo.context->drawText(font, run, origin, selectionStart, selectionEnd);
        }

        if (setShadow)
            paintInfo.context->clearShadow();
    }

    if (paintInfo.phase != PaintPhaseSelection && textPaintInfo.subphase == SVGTextPaintSubphaseForeground) {
        paintDocumentMarkers(paintInfo.context, tx, ty, styleToUse, font, false);

        if (useCustomUnderlines) {
            const Vector<CompositionUnderline>& underlines = text->document()->frame()->editor()->customCompositionUnderlines();
            size_t numUnderlines = underlines.size();
            
            for (size_t index = 0; index < numUnderlines; ++index) {
                const CompositionUnderline& underline = underlines[index];
                
                if (underline.endOffset <= start())
                    // underline is completely before this run.  This might be an underline that sits
                    // before the first run we draw, or underlines that were within runs we skipped 
                    // due to truncation.
                    continue;
                
                if (underline.startOffset <= end()) {
                    // underline intersects this run.  Paint it.
                    paintCompositionUnderline(paintInfo.context, tx, ty, underline);
                    if (underline.endOffset > end() + 1)
                        // underline also runs into the next run. Bail now, no more marker advancement.
                        break;
                } else
                    // underline is completely after this run, bail.  A later run will paint it.
                    break;
            }
        }
        
    }

    if (!ctm.isIdentity())
        paintInfo.context->concatCTM(ctm.inverse());
}

void SVGInlineTextBox::paintSelection(int boxStartOffset, const SVGChar& svgChar, const UChar*, int length, GraphicsContext* p, RenderStyle* style, const Font& font)
{
    if (selectionState() == RenderObject::SelectionNone)
        return;

    int startPos, endPos;
    selectionStartEnd(startPos, endPos);

    if (startPos >= endPos)
        return;

    Color textColor = style->visitedDependentColor(CSSPropertyColor);
    Color color = renderer()->selectionBackgroundColor();
    if (!color.isValid() || !color.alpha())
        return;

    // If the text color ends up being the same as the selection background, invert the selection
    // background.  This should basically never happen, since the selection has transparency.
    if (textColor == color)
        color = Color(0xff - color.red(), 0xff - color.green(), 0xff - color.blue());

    // Map from text box positions and a given start offset to chunk positions
    // 'boxStartOffset' represents the beginning of the text chunk.
    if ((startPos > boxStartOffset && endPos > boxStartOffset + length) || boxStartOffset >= endPos)
        return;

    if (endPos > boxStartOffset + length)
        endPos = boxStartOffset + length;

    if (startPos < boxStartOffset)
        startPos = boxStartOffset;

    ASSERT(startPos >= boxStartOffset);
    ASSERT(endPos <= boxStartOffset + length);
    ASSERT(startPos < endPos);

    p->save();

    int adjust = startPos >= boxStartOffset ? boxStartOffset : 0;
    p->drawHighlightForText(font, svgTextRunForInlineTextBox(textRenderer()->characters() + start() + boxStartOffset, length, style, this, svgChar.x),
                            IntPoint((int) svgChar.x, (int) svgChar.y - font.ascent()),
                            font.ascent() + font.descent(), color, style->colorSpace(), startPos - adjust, endPos - adjust);

    p->restore();
}

static inline Path pathForDecoration(ETextDecoration decoration, RenderObject* object, float x, float y, float width)
{
    float thickness = SVGRenderStyle::cssPrimitiveToLength(object, object->style()->svgStyle()->strokeWidth(), 1.0f);

    const Font& font = object->style()->font();
    thickness = max(thickness * powf(font.size(), 2.0f) / font.unitsPerEm(), 1.0f);

    if (decoration == UNDERLINE)
        y += thickness * 1.5f; // For compatibility with Batik/Opera
    else if (decoration == OVERLINE)
        y += thickness;

    float halfThickness = thickness / 2.0f;
    return Path::createRectangle(FloatRect(x + halfThickness, y, width - 2.0f * halfThickness, thickness));
}

void SVGInlineTextBox::paintDecoration(ETextDecoration decoration, GraphicsContext* context, int tx, int ty, int width, const SVGChar& svgChar, const SVGTextDecorationInfo& info)
{
    if (renderer()->style()->visibility() != VISIBLE)
        return;

    // This function does NOT accept combinated text decorations. It's meant to be invoked for just one.
    ASSERT(decoration == TDNONE || decoration == UNDERLINE || decoration == OVERLINE || decoration == LINE_THROUGH || decoration == BLINK);

    bool isFilled = info.fillServerMap.contains(decoration);
    bool isStroked = info.strokeServerMap.contains(decoration);

    if (!isFilled && !isStroked)
        return;

    int baseline = renderer()->style(m_firstLine)->font().ascent();
    if (decoration == UNDERLINE)
        ty += baseline;
    else if (decoration == LINE_THROUGH)
        ty += 2 * baseline / 3;

    context->save();
    context->beginPath();

    AffineTransform ctm = svgChar.characterTransform();
    if (!ctm.isIdentity())
        context->concatCTM(ctm);

    if (isFilled) {
        if (RenderObject* fillObject = info.fillServerMap.get(decoration)) {
            if (RenderSVGResource* fillPaintingResource = RenderSVGResource::fillPaintingResource(fillObject, fillObject->style())) {
                context->addPath(pathForDecoration(decoration, fillObject, tx, ty, width));
                if (fillPaintingResource->applyResource(fillObject, fillObject->style(), context, ApplyToFillMode))
                    fillPaintingResource->postApplyResource(fillObject, context, ApplyToFillMode);
            }
        }
    }

    if (isStroked) {
        if (RenderObject* strokeObject = info.strokeServerMap.get(decoration)) {
            if (RenderSVGResource* strokePaintingResource = RenderSVGResource::strokePaintingResource(strokeObject, strokeObject->style())) {
                context->addPath(pathForDecoration(decoration, strokeObject, tx, ty, width));
                if (strokePaintingResource->applyResource(strokeObject, strokeObject->style(), context, ApplyToStrokeMode))
                    strokePaintingResource->postApplyResource(strokeObject, context, ApplyToStrokeMode);
            }
        }
    }

    context->restore();
}

void SVGInlineTextBox::buildLayoutInformation(SVGCharacterLayoutInfo& info, SVGLastGlyphInfo& lastGlyph)
{
    RenderText* textRenderer = this->textRenderer();
    ASSERT(textRenderer);

    RenderStyle* style = textRenderer->style(isFirstLineStyle());
    ASSERT(style);

    const Font& font = style->font();
    const UChar* characters = textRenderer->characters();

    TextDirection textDirection = direction();
    unsigned startPosition = start();
    unsigned endPosition = end();
    unsigned length = len();

    const SVGRenderStyle* svgStyle = style->svgStyle();
    bool isVerticalText = isVerticalWritingMode(svgStyle);

    int charsConsumed = 0;
    for (unsigned i = 0; i < length; i += charsConsumed) {
        SVGChar svgChar;

        if (info.inPathLayout())
            svgChar.pathData = SVGCharOnPath::create();

        float glyphWidth = 0.0f;
        float glyphHeight = 0.0f;

        int extraCharsAvailable = length - i - 1;

        String unicodeStr;
        String glyphName;
        if (textDirection == RTL) {
            glyphWidth = calculateGlyphWidth(style, endPosition - i, extraCharsAvailable, charsConsumed, glyphName);
            glyphHeight = calculateGlyphHeight(style, endPosition - i, extraCharsAvailable);
            unicodeStr = String(characters + endPosition - i, charsConsumed);
        } else {
            glyphWidth = calculateGlyphWidth(style, startPosition + i, extraCharsAvailable, charsConsumed, glyphName);
            glyphHeight = calculateGlyphHeight(style, startPosition + i, extraCharsAvailable);
            unicodeStr = String(characters + startPosition + i, charsConsumed);
        }

        bool assignedX = false;
        bool assignedY = false;

        if (info.xValueAvailable() && (!info.inPathLayout() || (info.inPathLayout() && !isVerticalText))) {
            if (!isVerticalText)
                svgChar.newTextChunk = true;

            assignedX = true;
            svgChar.drawnSeperated = true;
            info.curx = info.xValueNext();
        }

        if (info.yValueAvailable() && (!info.inPathLayout() || (info.inPathLayout() && isVerticalText))) {
            if (isVerticalText)
                svgChar.newTextChunk = true;

            assignedY = true;
            svgChar.drawnSeperated = true;
            info.cury = info.yValueNext();
        }

        float dx = 0.0f;
        float dy = 0.0f;

        // Apply x-axis shift
        if (info.dxValueAvailable()) {
            svgChar.drawnSeperated = true;

            dx = info.dxValueNext();
            info.dx += dx;

            if (!info.inPathLayout())
                info.curx += dx;
        }

        // Apply y-axis shift
        if (info.dyValueAvailable()) {
            svgChar.drawnSeperated = true;

            dy = info.dyValueNext();
            info.dy += dy;

            if (!info.inPathLayout())
                info.cury += dy;
        }

        // Take letter & word spacing and kerning into account
        float spacing = font.letterSpacing() + calculateCSSKerning(style);

        const UChar* currentCharacter = characters + (textDirection == RTL ? endPosition - i : startPosition + i);
        const UChar* lastCharacter = 0;

        if (textDirection == RTL) {
            if (i < endPosition)
                lastCharacter = characters + endPosition - i +  1;
        } else {
            if (i > 0)
                lastCharacter = characters + startPosition + i - 1;
        }

        // FIXME: SVG Kerning doesn't get applied on texts on path.
        bool appliedSVGKerning = applySVGKerning(info, style, lastGlyph, unicodeStr, glyphName, isVerticalText);
        if (info.nextDrawnSeperated || spacing != 0.0f || appliedSVGKerning) {
            info.nextDrawnSeperated = false;
            svgChar.drawnSeperated = true;
        }

        if (currentCharacter && Font::treatAsSpace(*currentCharacter) && lastCharacter && !Font::treatAsSpace(*lastCharacter)) {
            spacing += font.wordSpacing();

            if (spacing != 0.0f && !info.inPathLayout())
                info.nextDrawnSeperated = true;
        }

        float orientationAngle = glyphOrientationToAngle(svgStyle, isVerticalText, *currentCharacter);

        float xOrientationShift = 0.0f;
        float yOrientationShift = 0.0f;
        float glyphAdvance = applyGlyphAdvanceAndShiftRespectingOrientation(isVerticalText, orientationAngle, glyphWidth, glyphHeight,
                                                                            font, svgChar, xOrientationShift, yOrientationShift);

        // Handle textPath layout mode
        if (info.inPathLayout()) {
            float extraAdvance = isVerticalText ? dy : dx;
            float newOffset = FLT_MIN;

            if (assignedX && !isVerticalText)
                newOffset = info.curx;
            else if (assignedY && isVerticalText)
                newOffset = info.cury;

            float correctedGlyphAdvance = glyphAdvance;

            // Handle lengthAdjust="spacingAndGlyphs" by specifying per-character scale operations
            if (info.pathTextLength && info.pathChunkLength) { 
                if (isVerticalText) {
                    svgChar.pathData->yScale = info.pathChunkLength / info.pathTextLength;
                    spacing *= svgChar.pathData->yScale;
                    correctedGlyphAdvance *= svgChar.pathData->yScale;
                } else {
                    svgChar.pathData->xScale = info.pathChunkLength / info.pathTextLength;
                    spacing *= svgChar.pathData->xScale;
                    correctedGlyphAdvance *= svgChar.pathData->xScale;
                }
            }

            // Handle letter & word spacing on text path
            float pathExtraAdvance = info.pathExtraAdvance;
            info.pathExtraAdvance += spacing;

            svgChar.pathData->hidden = !info.nextPathLayoutPointAndAngle(correctedGlyphAdvance, extraAdvance, newOffset);
            svgChar.drawnSeperated = true;

            info.pathExtraAdvance = pathExtraAdvance;
        }

        // Apply rotation
        if (info.angleValueAvailable())
            info.angle = info.angleValueNext();

        // Apply baseline-shift
        if (info.baselineShiftValueAvailable()) {
            svgChar.drawnSeperated = true;
            float shift = info.baselineShiftValueNext();

            if (isVerticalText)
                info.shiftx += shift;
            else
                info.shifty -= shift;
        }

        // Take dominant-baseline / alignment-baseline into account
        yOrientationShift += alignmentBaselineToShift(isVerticalText, textRenderer, font);

        svgChar.x = info.curx;
        svgChar.y = info.cury;
        svgChar.angle = info.angle;

        // For text paths any shift (dx/dy/baseline-shift) has to be applied after the rotation
        if (!info.inPathLayout()) {
            svgChar.x += info.shiftx + xOrientationShift;
            svgChar.y += info.shifty + yOrientationShift;

            if (orientationAngle != 0.0f)
                svgChar.angle += orientationAngle;

            if (svgChar.angle != 0.0f)
                svgChar.drawnSeperated = true;
        } else {
            svgChar.pathData->orientationAngle = orientationAngle;

            if (isVerticalText)
                svgChar.angle -= 90.0f;

            svgChar.pathData->xShift = info.shiftx + xOrientationShift;
            svgChar.pathData->yShift = info.shifty + yOrientationShift;

            // Translate to glyph midpoint
            if (isVerticalText) {
                svgChar.pathData->xShift += info.dx;
                svgChar.pathData->yShift -= glyphAdvance / 2.0f;
            } else {
                svgChar.pathData->xShift -= glyphAdvance / 2.0f;
                svgChar.pathData->yShift += info.dy;
            }
        }

        // Advance to new position
        if (isVerticalText) {
            svgChar.drawnSeperated = true;
            info.cury += glyphAdvance + spacing;
        } else
            info.curx += glyphAdvance + spacing;

        // Advance to next character group
        for (int k = 0; k < charsConsumed; ++k) {
            info.svgChars.append(svgChar);
            info.processedSingleCharacter();
            svgChar.drawnSeperated = false;
            svgChar.newTextChunk = false;
        }
    }
}

} // namespace WebCore

#endif