SvgTextBase.cs 37.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using Svg.DataTypes;
using System.Linq;
11
12
using System.Globalization;

13
14
15
16
namespace Svg
{
    public abstract class SvgTextBase : SvgVisualElement
    {
17
18
19
20
        [CLSCompliant(false)] protected SvgUnitCollection _x = new SvgUnitCollection();
        [CLSCompliant(false)] protected SvgUnitCollection _y = new SvgUnitCollection();
        [CLSCompliant(false)] protected SvgUnitCollection _dy = new SvgUnitCollection();
        [CLSCompliant(false)] protected SvgUnitCollection _dx = new SvgUnitCollection();
Eric Domke's avatar
Eric Domke committed
21
22
        private string _rotate;
        private List<float> _rotations = new List<float>();
23

24
25
26
27
28
29
        /// <summary>
        /// Gets or sets the text to be rendered.
        /// </summary>
        public virtual string Text
        {
            get { return base.Content; }
30
31
32
33
34
35
36
37
38
39
            set {
                Nodes.Clear();
                Children.Clear();
                if(value != null)
                {
                    Nodes.Add(new SvgContentNode { Content = value });
                }
                this.IsPathDirty = true;
                Content = value;
            }
40
41
        }

Eric Domke's avatar
Eric Domke committed
42
43
44
45
46
47
        public override XmlSpaceHandling SpaceHandling
        {
            get { return base.SpaceHandling; }
            set { base.SpaceHandling = value; this.IsPathDirty = true; }
        }

48
49
50
51
52
        /// <summary>
        /// Gets or sets the X.
        /// </summary>
        /// <value>The X.</value>
        [SvgAttribute("x")]
53
        public virtual SvgUnitCollection X
54
        {
55
56
57
58
59
60
61
62
63
64
            get { return this._x; }
            set
            {
                if (_x != value)
                {
                    this._x = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "x", Value = value });
                }
            }
65
66
67
68
69
70
71
        }

        /// <summary>
        /// Gets or sets the dX.
        /// </summary>
        /// <value>The dX.</value>
        [SvgAttribute("dx")]
72
        public virtual SvgUnitCollection Dx
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
        {
            get { return this._dx; }
            set
            {
                if (_dx != value)
                {
                    this._dx = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "dx", Value = value });
                }
            }
        }

        /// <summary>
        /// Gets or sets the Y.
        /// </summary>
        /// <value>The Y.</value>
        [SvgAttribute("y")]
91
        public virtual SvgUnitCollection Y
92
        {
93
94
95
96
97
98
99
100
101
102
            get { return this._y; }
            set
            {
                if (_y != value)
                {
                    this._y = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "y", Value = value });
                }
            }
103
104
105
106
107
108
109
        }

        /// <summary>
        /// Gets or sets the dY.
        /// </summary>
        /// <value>The dY.</value>
        [SvgAttribute("dy")]
110
        public virtual SvgUnitCollection Dy
111
112
113
114
115
116
117
118
119
120
121
122
123
        {
            get { return this._dy; }
            set
            {
                if (_dy != value)
                {
                    this._dy = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "dy", Value = value });
                }
            }
        }

Eric Domke's avatar
Eric Domke committed
124
125
126
127
128
129
130
131
132
133
134
135
136
137
        /// <summary>
        /// Gets or sets the rotate.
        /// </summary>
        /// <value>The rotate.</value>
        [SvgAttribute("rotate")]
        public virtual string Rotate
        {
            get { return this._rotate; }
            set
            {
                if (_rotate != value)
                {
                    this._rotate = value;
                    this._rotations.Clear();
138
                    this._rotations.AddRange(from r in _rotate.Split(new char[] { ',', ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries) select float.Parse(r));
Eric Domke's avatar
Eric Domke committed
139
140
141
142
143
144
145
146
147
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "rotate", Value = value });
                }
            }
        }

        /// <summary>
        /// The pre-calculated length of the text
        /// </summary>
Eric Domke's avatar
Eric Domke committed
148
        [SvgAttribute("textLength", true)]
Eric Domke's avatar
Eric Domke committed
149
150
151
152
153
154
155
156
157
158
        public virtual SvgUnit TextLength
        {
            get { return (this.Attributes["textLength"] == null ? SvgUnit.None : (SvgUnit)this.Attributes["textLength"]); }
            set { this.Attributes["textLength"] = value; this.IsPathDirty = true; }
        }

        /// <summary>
        /// Gets or sets the text anchor.
        /// </summary>
        /// <value>The text anchor.</value>
Eric Domke's avatar
Eric Domke committed
159
        [SvgAttribute("lengthAdjust", true)]
Eric Domke's avatar
Eric Domke committed
160
161
        public virtual SvgTextLengthAdjust LengthAdjust
        {
162
            get { return (this.Attributes["lengthAdjust"] == null) ? SvgTextLengthAdjust.Spacing : (SvgTextLengthAdjust)this.Attributes["lengthAdjust"]; }
Eric Domke's avatar
Eric Domke committed
163
164
165
            set { this.Attributes["lengthAdjust"] = value; this.IsPathDirty = true; }
        }

166
167
168
        /// <summary>
        /// Specifies spacing behavior between text characters.
        /// </summary>
Eric Domke's avatar
Eric Domke committed
169
        [SvgAttribute("letter-spacing", true)]
170
171
        public virtual SvgUnit LetterSpacing
        {
Eric Domke's avatar
Eric Domke committed
172
173
            get { return (this.Attributes["letter-spacing"] == null ? SvgUnit.None : (SvgUnit)this.Attributes["letter-spacing"]); }
            set { this.Attributes["letter-spacing"] = value; this.IsPathDirty = true; }
174
175
176
177
178
        }

        /// <summary>
        /// Specifies spacing behavior between words.
        /// </summary>
Eric Domke's avatar
Eric Domke committed
179
        [SvgAttribute("word-spacing", true)]
180
181
        public virtual SvgUnit WordSpacing
        {
Eric Domke's avatar
Eric Domke committed
182
183
            get { return (this.Attributes["word-spacing"] == null ? SvgUnit.None : (SvgUnit)this.Attributes["word-spacing"]); }
            set { this.Attributes["word-spacing"] = value; this.IsPathDirty = true; }
184
185
186
187
188
189
        }

        /// <summary>
        /// Gets or sets the fill.
        /// </summary>
        /// <remarks>
190
        /// <para>Unlike other <see cref="SvgVisualElement"/>s, <see cref="SvgText"/> has a default fill of black rather than transparent.</para>
191
192
193
194
        /// </remarks>
        /// <value>The fill.</value>
        public override SvgPaintServer Fill
        {
195
            get { return (this.Attributes["fill"] == null) ? new SvgColourServer(System.Drawing.Color.Black) : (SvgPaintServer)this.Attributes["fill"]; }
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
            set { this.Attributes["fill"] = value; }
        }

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
        /// </returns>
        public override string ToString()
        {
            return this.Text;
        }

        /// <summary>
        /// Gets the bounds of the element.
        /// </summary>
Tebjan Halm's avatar
Tebjan Halm committed
213
214
        /// <value>The bounds.</value>
        public override System.Drawing.RectangleF Bounds
215
        {
216
            get
217
            {
Tebjan Halm's avatar
Tebjan Halm committed
218
219
220
221
222
                var path = this.Path(null);
                foreach (var elem in this.Children.OfType<SvgVisualElement>())
                {
                    path.AddPath(elem.Path(null), false);
                }
223
                return path.GetBounds();
224
            }
225
226
227
228
229
        }

        /// <summary>
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object.
        /// </summary>
Eric Domke's avatar
Eric Domke committed
230
        /// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
231
        /// <remarks>Necessary to make sure that any internal tspan elements get rendered as well</remarks>
Eric Domke's avatar
Eric Domke committed
232
        protected override void Render(ISvgRenderer renderer)
233
        {
234
            if ((this.Path(renderer) != null) && this.Visible && this.Displayable)
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
            {
                this.PushTransforms(renderer);
                this.SetClip(renderer);

                // If this element needs smoothing enabled turn anti-aliasing on
                if (this.RequiresSmoothRendering)
                {
                    renderer.SmoothingMode = SmoothingMode.AntiAlias;
                }

                this.RenderFill(renderer);
                this.RenderStroke(renderer);
                this.RenderChildren(renderer);

                // Reset the smoothing mode
                if (this.RequiresSmoothRendering && renderer.SmoothingMode == SmoothingMode.AntiAlias)
                {
                    renderer.SmoothingMode = SmoothingMode.Default;
                }

                this.ResetClip(renderer);
                this.PopTransforms(renderer);
            }
        }

Eric Domke's avatar
Eric Domke committed
260
        internal virtual IEnumerable<ISvgNode> GetContentNodes()
261
        {
262
            return (this.Nodes == null || this.Nodes.Count < 1 ? this.Children.OfType<ISvgNode>().Where(o => !(o is ISvgDescriptiveElement)) : this.Nodes);
263
        }
Eric Domke's avatar
Eric Domke committed
264
        protected virtual GraphicsPath GetBaselinePath(ISvgRenderer renderer)
265
        {
Eric Domke's avatar
Eric Domke committed
266
            return null;
267
        }
Eric Domke's avatar
Eric Domke committed
268
        protected virtual float GetAuthorPathLength()
269
        {
Eric Domke's avatar
Eric Domke committed
270
            return 0;
271
272
        }

Eric Domke's avatar
Eric Domke committed
273
        private GraphicsPath _path;
274
275
276
277
278

        /// <summary>
        /// Gets the <see cref="GraphicsPath"/> for this element.
        /// </summary>
        /// <value></value>
Ritch Melton's avatar
Ritch Melton committed
279
        public override GraphicsPath Path(ISvgRenderer renderer)
280
        {
281
            //if there is a TSpan inside of this text element then path should not be null (even if this text is empty!)
282
283
284
            var nodes = GetContentNodes().Where(x => x is SvgContentNode &&
                                                     string.IsNullOrEmpty(x.Content.Trim(new[] { '\r', '\n', '\t' })));

Ritch Melton's avatar
Ritch Melton committed
285
            if (_path == null || IsPathDirty || nodes.Count() == 1)
286
            {
287
                renderer = (renderer ?? SvgRenderer.FromNull());
Ritch Melton's avatar
Ritch Melton committed
288
                SetPath(new TextDrawingState(renderer, this));
Eric Domke's avatar
Eric Domke committed
289
290
291
            }
            return _path;
        }
292

Eric Domke's avatar
Eric Domke committed
293
294
295
296
        private void SetPath(TextDrawingState state)
        {
            SetPath(state, true);
        }
297

Eric Domke's avatar
Eric Domke committed
298
299
300
301
302
        /// <summary>
        /// Sets the path on this element and all child elements.  Uses the state
        /// object to track the state of the drawing
        /// </summary>
        /// <param name="state">State of the drawing operation</param>
303
        /// <param name="doMeasurements">If true, calculate and apply text length adjustments.</param>
Eric Domke's avatar
Eric Domke committed
304
305
306
307
        private void SetPath(TextDrawingState state, bool doMeasurements)
        {
            TextDrawingState origState = null;
            bool alignOnBaseline = state.BaselinePath != null && (this.TextAnchor == SvgTextAnchor.Middle || this.TextAnchor == SvgTextAnchor.End);
308

Eric Domke's avatar
Eric Domke committed
309
310
311
312
313
314
315
            if (doMeasurements)
            {
                if (this.TextLength != SvgUnit.None)
                {
                    origState = state.Clone();
                }
                else if (alignOnBaseline)
316
                {
Eric Domke's avatar
Eric Domke committed
317
318
                    origState = state.Clone();
                    state.BaselinePath = null;
319
                }
Eric Domke's avatar
Eric Domke committed
320
            }
321

Eric Domke's avatar
Eric Domke committed
322
323
            foreach (var node in GetContentNodes())
            {
324
325
326
                SvgTextBase textNode = node as SvgTextBase;

                if (textNode == null)
327
                {
328
                    if (!string.IsNullOrEmpty(node.Content)) state.DrawString(PrepareText(node.Content));
329
                }
Eric Domke's avatar
Eric Domke committed
330
                else
331
                {
332
333
334
                    TextDrawingState newState= new TextDrawingState(state, textNode);

                    textNode.SetPath(newState);
Eric Domke's avatar
Eric Domke committed
335
336
                    state.NumChars += newState.NumChars;
                    state.Current = newState.Current;
337
                }
Eric Domke's avatar
Eric Domke committed
338
            }
339

Eric Domke's avatar
Eric Domke committed
340
            var path = state.GetPath() ?? new GraphicsPath();
341

Eric Domke's avatar
Eric Domke committed
342
343
344
345
            // Apply any text length adjustments
            if (doMeasurements)
            {
                if (this.TextLength != SvgUnit.None)
346
                {
Eric Domke's avatar
Eric Domke committed
347
                    var specLength = this.TextLength.ToDeviceValue(state.Renderer, UnitRenderingType.Horizontal, this);
348
                    var actLength = state.TextBounds.Width;
Eric Domke's avatar
Eric Domke committed
349
350
                    var diff = (actLength - specLength);
                    if (Math.Abs(diff) > 1.5)
351
                    {
352
                        if (this.LengthAdjust == SvgTextLengthAdjust.Spacing)
Eric Domke's avatar
Eric Domke committed
353
                        {
354
355
356
357
358
359
                            if (this.X.Count < 2)
                            {
                                origState.LetterSpacingAdjust = -1 * diff / (state.NumChars - origState.NumChars - 1);
                                SetPath(origState, false);
                                return;
                            }
Eric Domke's avatar
Eric Domke committed
360
361
362
                        }
                        else
                        {
Eric Domke's avatar
Eric Domke committed
363
364
                            using (var matrix = new Matrix())
                            {
365
                                matrix.Translate(-1 * state.TextBounds.X, 0, MatrixOrder.Append);
Eric Domke's avatar
Eric Domke committed
366
                                matrix.Scale(specLength / actLength, 1, MatrixOrder.Append);
367
                                matrix.Translate(state.TextBounds.X, 0, MatrixOrder.Append);
Eric Domke's avatar
Eric Domke committed
368
369
                                path.Transform(matrix);
                            }
Eric Domke's avatar
Eric Domke committed
370
371
372
373
                        }
                    }
                }
                else if (alignOnBaseline)
374
                {
Eric Domke's avatar
Eric Domke committed
375
376
                    var bounds = path.GetBounds();
                    if (this.TextAnchor == SvgTextAnchor.Middle)
377
                    {
Eric Domke's avatar
Eric Domke committed
378
                        origState.StartOffsetAdjust = -1 * bounds.Width / 2;
379
380
381
                    }
                    else
                    {
Eric Domke's avatar
Eric Domke committed
382
                        origState.StartOffsetAdjust = -1 * bounds.Width;
383
                    }
Eric Domke's avatar
Eric Domke committed
384
385
                    SetPath(origState, false);
                    return;
386
387
                }
            }
Eric Domke's avatar
Eric Domke committed
388
389
390
391


            _path = path;
            this.IsPathDirty = false;
392
393
        }

394
395
        private static readonly Regex MultipleSpaces = new Regex(@" {2,}", RegexOptions.Compiled);

396
        /// <summary>
397
        /// Prepare the text according to the whitespace handling rules and text transformations.  <see href="http://www.w3.org/TR/SVG/text.html">SVG Spec</see>.
398
399
400
        /// </summary>
        /// <param name="value">Text to be prepared</param>
        /// <returns>Prepared text</returns>
Eric Domke's avatar
Eric Domke committed
401
        protected string PrepareText(string value)
402
        {
403
            value = ApplyTransformation(value);
Eric Domke's avatar
Eric Domke committed
404
            if (this.SpaceHandling == XmlSpaceHandling.preserve)
405
            {
406
                return value.Replace('\t', ' ').Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
407
408
409
            }
            else
            {
410
411
                var convValue = MultipleSpaces.Replace(value.Replace("\r", "").Replace("\n", "").Replace('\t', ' '), " ");
                return convValue;
412
413
414
            }
        }

415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
        private string ApplyTransformation(string value)
        {
            switch (this.TextTransformation)
            {
                case SvgTextTransformation.Capitalize:
                    return value.ToUpper();

                case SvgTextTransformation.Uppercase:
                    return value.ToUpper();

                case SvgTextTransformation.Lowercase:
                    return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(value);
            }

            return value;
        }

432
        [SvgAttribute("onchange")]
433
        public event EventHandler<StringArg> Change;
434
435

        //change
436
437
        protected void OnChange(string newString, string sessionID)
        {
438
            RaiseChange(this, new StringArg { s = newString, SessionID = sessionID });
439
        }
440

441
442
        protected void RaiseChange(object sender, StringArg s)
        {
443
            var handler = Change;
444
445
446
447
448
449
            if (handler != null)
            {
                handler(sender, s);
            }
        }

Eric Domke's avatar
Eric Domke committed
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466


        //private static GraphicsPath GetPath(string text, Font font)
        //{
        //    var fontMetrics = (from c in text.Distinct()
        //                       select new { Char = c, Metrics = Metrics(c, font) }).
        //                       ToDictionary(c => c.Char, c=> c.Metrics);
        //    // Measure each character and check the metrics against the overall metrics of rendering
        //    // an entire word with kerning.
        //}
        //private static RectangleF Metrics(char c, Font font)
        //{
        //    var path = new GraphicsPath();
        //    path.AddString(c.ToString(), font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), StringFormat.GenericTypographic);
        //    return path.GetBounds();
        //}

467
#if Net4
468
469
470
471
472
473
        public override void RegisterEvents(ISvgEventCaller caller)
        {
            //register basic events
            base.RegisterEvents(caller); 
            
            //add change event for text
474
            caller.RegisterAction<string, string>(this.ID + "/onchange", OnChange);
475
476
477
478
479
480
481
482
483
484
485
        }
        
        public override void UnregisterEvents(ISvgEventCaller caller)
        {
            //unregister base events
            base.UnregisterEvents(caller);
            
            //unregister change event
            caller.UnregisterAction(this.ID + "/onchange");
            
        }
486
#endif
487
488
489

        private class FontBoundable : ISvgBoundable
        {
Eric Domke's avatar
Eric Domke committed
490
491
            private IFontDefn _font;
            private float _width = 1;
492

Eric Domke's avatar
Eric Domke committed
493
            public FontBoundable(IFontDefn font)
494
495
496
            {
                _font = font;
            }
Eric Domke's avatar
Eric Domke committed
497
            public FontBoundable(IFontDefn font, float width)
498
499
            {
                _font = font;
Eric Domke's avatar
Eric Domke committed
500
                _width = width;
501
502
            }

Tebjan Halm's avatar
Tebjan Halm committed
503
504
505
506
507
508
509
510
511
512
513
            public PointF Location
            {
                get { return PointF.Empty; }
            }

            public SizeF Size
            {
                get { return new SizeF(_width, _font.Size); }
            }

            public RectangleF Bounds
514
            {
Tebjan Halm's avatar
Tebjan Halm committed
515
                get { return new RectangleF(this.Location, this.Size); }
516
517
            }
        }
Eric Domke's avatar
Eric Domke committed
518
519
520
521
522
523
524
525
526
527
528

        private class TextDrawingState
        {
            private float _xAnchor = float.MinValue;
            private IList<GraphicsPath> _anchoredPaths = new List<GraphicsPath>();
            private GraphicsPath _currPath = null;
            private GraphicsPath _finalPath = null;
            private float _authorPathLength = 0;

            public GraphicsPath BaselinePath { get; set; }
            public PointF Current { get; set; }
529
            public RectangleF TextBounds { get; set; }
Eric Domke's avatar
Eric Domke committed
530
531
532
533
534
535
536
537
538
539
540
541
542
            public SvgTextBase Element { get; set; }
            public float LetterSpacingAdjust { get; set; }
            public int NumChars { get; set; }
            public TextDrawingState Parent { get; set; }
            public ISvgRenderer Renderer { get; set; }
            public float StartOffsetAdjust { get; set; }

            private TextDrawingState() { }
            public TextDrawingState(ISvgRenderer renderer, SvgTextBase element)
            {
                this.Element = element;
                this.Renderer = renderer;
                this.Current = PointF.Empty;
543
                this.TextBounds = RectangleF.Empty;
Eric Domke's avatar
Eric Domke committed
544
545
546
547
548
549
550
551
552
553
                _xAnchor = 0;
                this.BaselinePath = element.GetBaselinePath(renderer);
                _authorPathLength = element.GetAuthorPathLength();
            }
            public TextDrawingState(TextDrawingState parent, SvgTextBase element)
            {
                this.Element = element;
                this.Renderer = parent.Renderer;
                this.Parent = parent;
                this.Current = parent.Current;
554
                this.TextBounds = parent.TextBounds;
Eric Domke's avatar
Eric Domke committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
                this.BaselinePath = element.GetBaselinePath(parent.Renderer) ?? parent.BaselinePath;
                var currPathLength = element.GetAuthorPathLength();
                _authorPathLength = currPathLength == 0 ? parent._authorPathLength : currPathLength;
            }

            public GraphicsPath GetPath()
            {
                FlushPath();
                return _finalPath;
            }

            public TextDrawingState Clone()
            {
                var result = new TextDrawingState();
                result._anchoredPaths = this._anchoredPaths.ToList();
                result.BaselinePath = this.BaselinePath;
                result._xAnchor = this._xAnchor;
                result.Current = this.Current;
573
                result.TextBounds = this.TextBounds;
Eric Domke's avatar
Eric Domke committed
574
575
576
577
578
579
580
581
582
583
584
585
                result.Element = this.Element;
                result.NumChars = this.NumChars;
                result.Parent = this.Parent;
                result.Renderer = this.Renderer;
                return result;
            }

            public void DrawString(string value)
            {
                // Get any defined anchors
                var xAnchors = GetValues(value.Length, e => e._x, UnitRenderingType.HorizontalOffset);
                var yAnchors = GetValues(value.Length, e => e._y, UnitRenderingType.VerticalOffset);
Eric Domke's avatar
Eric Domke committed
586
                using (var font = this.Element.GetFont(this.Renderer))
Eric Domke's avatar
Eric Domke committed
587
                {
Eric Domke's avatar
Eric Domke committed
588
589
590
591
                    var fontBaselineHeight = font.Ascent(this.Renderer);
                    PathStatistics pathStats = null;
                    var pathScale = 1.0;
                    if (BaselinePath != null)
Eric Domke's avatar
Eric Domke committed
592
                    {
Eric Domke's avatar
Eric Domke committed
593
594
                        pathStats = new PathStatistics(BaselinePath.PathData);
                        if (_authorPathLength > 0) pathScale = _authorPathLength / pathStats.TotalLength;
Eric Domke's avatar
Eric Domke committed
595
596
                    }

Eric Domke's avatar
Eric Domke committed
597
598
599
600
601
602
603
                    // Get all of the offsets (explicit and defined by spacing)
                    IList<float> xOffsets;
                    IList<float> yOffsets;
                    IList<float> rotations;
                    float baselineShift = 0.0f;

                    try
Eric Domke's avatar
Eric Domke committed
604
                    {
Eric Domke's avatar
Eric Domke committed
605
606
607
608
                        this.Renderer.SetBoundable(new FontBoundable(font, (float)(pathStats == null ? 1 : pathStats.TotalLength)));
                        xOffsets = GetValues(value.Length, e => e._dx, UnitRenderingType.Horizontal);
                        yOffsets = GetValues(value.Length, e => e._dy, UnitRenderingType.Vertical);
                        if (StartOffsetAdjust != 0.0f)
Eric Domke's avatar
Eric Domke committed
609
                        {
Eric Domke's avatar
Eric Domke committed
610
                            if (xOffsets.Count < 1)
Eric Domke's avatar
Eric Domke committed
611
                            {
Eric Domke's avatar
Eric Domke committed
612
                                xOffsets.Add(StartOffsetAdjust);
Eric Domke's avatar
Eric Domke committed
613
614
615
                            }
                            else
                            {
Eric Domke's avatar
Eric Domke committed
616
                                xOffsets[0] += StartOffsetAdjust;
Eric Domke's avatar
Eric Domke committed
617
618
619
                            }
                        }

Eric Domke's avatar
Eric Domke committed
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
                        if (this.Element.LetterSpacing.Value != 0.0f || this.Element.WordSpacing.Value != 0.0f || this.LetterSpacingAdjust != 0.0f)
                        {
                            var spacing = this.Element.LetterSpacing.ToDeviceValue(this.Renderer, UnitRenderingType.Horizontal, this.Element) + this.LetterSpacingAdjust;
                            var wordSpacing = this.Element.WordSpacing.ToDeviceValue(this.Renderer, UnitRenderingType.Horizontal, this.Element);
                            if (this.Parent == null && this.NumChars == 0 && xOffsets.Count < 1) xOffsets.Add(0);
                            for (int i = (this.Parent == null && this.NumChars == 0 ? 1 : 0); i < value.Length; i++)
                            {
                                if (i >= xOffsets.Count)
                                {
                                    xOffsets.Add(spacing + (char.IsWhiteSpace(value[i]) ? wordSpacing : 0));
                                }
                                else
                                {
                                    xOffsets[i] += spacing + (char.IsWhiteSpace(value[i]) ? wordSpacing : 0);
                                }
                            }
                        }
Eric Domke's avatar
Eric Domke committed
637

Eric Domke's avatar
Eric Domke committed
638
                        rotations = GetValues(value.Length, e => e._rotations);
Eric Domke's avatar
Eric Domke committed
639

Eric Domke's avatar
Eric Domke committed
640
641
                        // Calculate Y-offset due to baseline shift.  Don't inherit the value so that it is not accumulated multiple times.               
                        var baselineShiftText = this.Element.Attributes.GetAttribute<string>("baseline-shift");
Eric Domke's avatar
Eric Domke committed
642

Eric Domke's avatar
Eric Domke committed
643
                        switch (baselineShiftText)
Eric Domke's avatar
Eric Domke committed
644
                        {
Eric Domke's avatar
Eric Domke committed
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
                            case null:
                            case "":
                            case "baseline":
                            case "inherit":
                                // do nothing
                                break;
                            case "sub":
                                baselineShift = new SvgUnit(SvgUnitType.Ex, 1).ToDeviceValue(this.Renderer, UnitRenderingType.Vertical, this.Element);
                                break;
                            case "super":
                                baselineShift = -1 * new SvgUnit(SvgUnitType.Ex, 1).ToDeviceValue(this.Renderer, UnitRenderingType.Vertical, this.Element);
                                break;
                            default:
                                var convert = new SvgUnitConverter();
                                var shiftUnit = (SvgUnit)convert.ConvertFromInvariantString(baselineShiftText);
                                baselineShift = -1 * shiftUnit.ToDeviceValue(this.Renderer, UnitRenderingType.Vertical, this.Element);
                                break;
Eric Domke's avatar
Eric Domke committed
662
                        }
Eric Domke's avatar
Eric Domke committed
663
664

                        if (baselineShift != 0.0f)
Eric Domke's avatar
Eric Domke committed
665
                        {
Eric Domke's avatar
Eric Domke committed
666
667
668
669
670
671
672
673
                            if (yOffsets.Any())
                            {
                                yOffsets[0] += baselineShift;
                            }
                            else
                            {
                                yOffsets.Add(baselineShift);
                            }
Eric Domke's avatar
Eric Domke committed
674
675
                        }
                    }
Eric Domke's avatar
Eric Domke committed
676
677
678
679
                    finally
                    {
                        this.Renderer.PopBoundable();
                    }
Eric Domke's avatar
Eric Domke committed
680

681
                    var xTextStart = Current.X;
Eric Domke's avatar
Eric Domke committed
682
683
684
685
686
687
688
689
690
                    // NOTE: Assuming a horizontal left-to-right font
                    // Render absolutely positioned items in the horizontal direction
                    var yPos = Current.Y;
                    for (int i = 0; i < xAnchors.Count - 1; i++)
                    {
                        FlushPath();
                        _xAnchor = xAnchors[i] + (xOffsets.Count > i ? xOffsets[i] : 0);
                        EnsurePath();
                        yPos = (yAnchors.Count > i ? yAnchors[i] : yPos) + (yOffsets.Count > i ? yOffsets[i] : 0);
Eric Domke's avatar
Eric Domke committed
691

692
                        xTextStart = xTextStart.Equals(Current.X) ? _xAnchor : xTextStart;
Eric Domke's avatar
Eric Domke committed
693
694
695
                        DrawStringOnCurrPath(value[i].ToString(), font, new PointF(_xAnchor, yPos),
                                             fontBaselineHeight, (rotations.Count > i ? rotations[i] : rotations.LastOrDefault()));
                    }
Eric Domke's avatar
Eric Domke committed
696

Eric Domke's avatar
Eric Domke committed
697
698
699
700
701
702
703
704
705
706
707
                    // Render any remaining characters
                    var renderChar = 0;
                    var xPos = this.Current.X;
                    if (xAnchors.Any())
                    {
                        FlushPath();
                        renderChar = xAnchors.Count - 1;
                        xPos = xAnchors.Last();
                        _xAnchor = xPos;
                    }
                    EnsurePath();
Eric Domke's avatar
Eric Domke committed
708
709


Eric Domke's avatar
Eric Domke committed
710
711
712
713
                    // Render individual characters as necessary
                    var lastIndividualChar = renderChar + Math.Max(Math.Max(Math.Max(Math.Max(xOffsets.Count, yOffsets.Count), yAnchors.Count), rotations.Count) - renderChar - 1, 0);
                    if (rotations.LastOrDefault() != 0.0f || pathStats != null) lastIndividualChar = value.Length;
                    if (lastIndividualChar > renderChar)
Eric Domke's avatar
Eric Domke committed
714
                    {
Eric Domke's avatar
Eric Domke committed
715
716
717
718
719
                        var charBounds = font.MeasureCharacters(this.Renderer, value.Substring(renderChar, Math.Min(lastIndividualChar + 1, value.Length) - renderChar));
                        PointF pathPoint;
                        float rotation;
                        float halfWidth;
                        for (int i = renderChar; i < lastIndividualChar; i++)
Eric Domke's avatar
Eric Domke committed
720
                        {
Eric Domke's avatar
Eric Domke committed
721
722
723
724
                            xPos += (float)pathScale * (xOffsets.Count > i ? xOffsets[i] : 0) + (charBounds[i - renderChar].X - (i == renderChar ? 0 : charBounds[i - renderChar - 1].X));
                            yPos = (yAnchors.Count > i ? yAnchors[i] : yPos) + (yOffsets.Count > i ? yOffsets[i] : 0);
                            if (pathStats == null)
                            {
725
                                xTextStart = xTextStart.Equals(Current.X) ? xPos : xTextStart;
Eric Domke's avatar
Eric Domke committed
726
727
728
729
730
731
732
733
734
735
736
737
                                DrawStringOnCurrPath(value[i].ToString(), font, new PointF(xPos, yPos),
                                                     fontBaselineHeight, (rotations.Count > i ? rotations[i] : rotations.LastOrDefault()));
                            }
                            else
                            {
                                xPos = Math.Max(xPos, 0);
                                halfWidth = charBounds[i - renderChar].Width / 2;
                                if (pathStats.OffsetOnPath(xPos + halfWidth))
                                {
                                    pathStats.LocationAngleAtOffset(xPos + halfWidth, out pathPoint, out rotation);
                                    pathPoint = new PointF((float)(pathPoint.X - halfWidth * Math.Cos(rotation * Math.PI / 180) - (float)pathScale * yPos * Math.Sin(rotation * Math.PI / 180)),
                                                           (float)(pathPoint.Y - halfWidth * Math.Sin(rotation * Math.PI / 180) + (float)pathScale * yPos * Math.Cos(rotation * Math.PI / 180)));
738
                                    xTextStart = xTextStart.Equals(Current.X) ? pathPoint.X : xTextStart;
Eric Domke's avatar
Eric Domke committed
739
740
741
742
743
744
745
746
747
                                    DrawStringOnCurrPath(value[i].ToString(), font, pathPoint, fontBaselineHeight, rotation);
                                }
                            }
                        }

                        // Add the kerning to the next character
                        if (lastIndividualChar < value.Length)
                        {
                            xPos += charBounds[charBounds.Count - 1].X - charBounds[charBounds.Count - 2].X;
Eric Domke's avatar
Eric Domke committed
748
749
750
                        }
                        else
                        {
Eric Domke's avatar
Eric Domke committed
751
                            xPos += charBounds.Last().Width;
Eric Domke's avatar
Eric Domke committed
752
753
754
                        }
                    }

Eric Domke's avatar
Eric Domke committed
755
756
                    // Render the string normally
                    if (lastIndividualChar < value.Length)
Eric Domke's avatar
Eric Domke committed
757
                    {
Eric Domke's avatar
Eric Domke committed
758
759
760
                        xPos += (xOffsets.Count > lastIndividualChar ? xOffsets[lastIndividualChar] : 0);
                        yPos = (yAnchors.Count > lastIndividualChar ? yAnchors[lastIndividualChar] : yPos) +
                                (yOffsets.Count > lastIndividualChar ? yOffsets[lastIndividualChar] : 0);
761
                        xTextStart = xTextStart.Equals(Current.X) ? xPos : xTextStart;
Eric Domke's avatar
Eric Domke committed
762
763
764
765
                        DrawStringOnCurrPath(value.Substring(lastIndividualChar), font, new PointF(xPos, yPos),
                                             fontBaselineHeight, rotations.LastOrDefault());
                        var bounds = font.MeasureString(this.Renderer, value.Substring(lastIndividualChar));
                        xPos += bounds.Width;
Eric Domke's avatar
Eric Domke committed
766
767
768
                    }


Eric Domke's avatar
Eric Domke committed
769
770
771
                    NumChars += value.Length;
                    // Undo any baseline shift.  This is not persisted, unlike normal vertical offsets.
                    this.Current = new PointF(xPos, yPos - baselineShift);
772
                    this.TextBounds = new RectangleF(xTextStart, 0, this.Current.X - xTextStart, 0);
Eric Domke's avatar
Eric Domke committed
773
                }
Eric Domke's avatar
Eric Domke committed
774
775
776
777
778
779
780
781
782
            }

            private void DrawStringOnCurrPath(string value, IFontDefn font, PointF location, float fontBaselineHeight, float rotation)
            {
                var drawPath = _currPath;
                if (rotation != 0.0f) drawPath = new GraphicsPath();
                font.AddStringToPath(this.Renderer, drawPath, value, new PointF(location.X, location.Y - fontBaselineHeight));
                if (rotation != 0.0f && drawPath.PointCount > 0)
                {
Eric Domke's avatar
Eric Domke committed
783
784
785
786
787
788
789
790
                    using (var matrix = new Matrix())
                    {
                        matrix.Translate(-1 * location.X, -1 * location.Y, MatrixOrder.Append);
                        matrix.Rotate(rotation, MatrixOrder.Append);
                        matrix.Translate(location.X, location.Y, MatrixOrder.Append);
                        drawPath.Transform(matrix);
                        _currPath.AddPath(drawPath, false);
                    }
Eric Domke's avatar
Eric Domke committed
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
                }

            }

            private void EnsurePath()
            {
                if (_currPath == null)
                {
                    _currPath = new GraphicsPath();
                    _currPath.StartFigure();

                    var currState = this;
                    while (currState != null && currState._xAnchor <= float.MinValue)
                    {
                        currState = currState.Parent;
                    }
                    currState._anchoredPaths.Add(_currPath);
                }
            }

            private void FlushPath()
            {
                if (_currPath != null)
                {
                    _currPath.CloseFigure();

                    // Abort on empty paths (e.g. rendering a space)
                    if (_currPath.PointCount < 1)
                    {
                        _anchoredPaths.Clear();
                        _xAnchor = float.MinValue;
                        _currPath = null;
                        return;
                    }

                    if (_xAnchor > float.MinValue)
                    {
                        float minX = float.MaxValue;
                        float maxX = float.MinValue;
                        RectangleF bounds;
                        foreach (var path in _anchoredPaths)
                        {
                            bounds = path.GetBounds();
                            if (bounds.Left < minX) minX = bounds.Left;
                            if (bounds.Right > maxX) maxX = bounds.Right;
                        }

Eric Domke's avatar
Eric Domke committed
838
                        var xOffset = 0f; //_xAnchor - minX;
Eric Domke's avatar
Eric Domke committed
839
840
                        switch (Element.TextAnchor)
                        {
841
842
843
                            case SvgTextAnchor.Middle:
                                if (_anchoredPaths.Count() == 1) xOffset -= this.TextBounds.Width / 2; 
                                else xOffset -= (maxX - minX) / 2;
Eric Domke's avatar
Eric Domke committed
844
845
                                break;
                            case SvgTextAnchor.End:
846
847
                                if (_anchoredPaths.Count() == 1) xOffset -= this.TextBounds.Width;
                                else xOffset -= (maxX - minX); 
Eric Domke's avatar
Eric Domke committed
848
849
850
851
852
                                break;
                        }

                        if (xOffset != 0)
                        {
Eric Domke's avatar
Eric Domke committed
853
                            using (var matrix = new Matrix())
Eric Domke's avatar
Eric Domke committed
854
                            {
Eric Domke's avatar
Eric Domke committed
855
856
857
858
859
                                matrix.Translate(xOffset, 0);
                                foreach (var path in _anchoredPaths)
                                {
                                    path.Transform(matrix);
                                }
Eric Domke's avatar
Eric Domke committed
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
                            }
                        }

                        _anchoredPaths.Clear();
                        _xAnchor = float.MinValue;

                    }

                    if (_finalPath == null)
                    {
                        _finalPath = _currPath;
                    }
                    else
                    {
                        _finalPath.AddPath(_currPath, false);
                    }

                    _currPath = null;
                }
            }

            private IList<float> GetValues(int maxCount, Func<SvgTextBase, IEnumerable<float>> listGetter)
            {
                var currState = this;
                int charCount = 0;
                var results = new List<float>();
                int resultCount = 0;

                while (currState != null)
                {
                    charCount += currState.NumChars;
                    results.AddRange(listGetter.Invoke(currState.Element).Skip(charCount).Take(maxCount));
                    if (results.Count > resultCount)
                    {
                        maxCount -= results.Count - resultCount;
                        charCount += results.Count - resultCount;
                        resultCount = results.Count;
                    }

                    if (maxCount < 1) return results;

                    currState = currState.Parent;
                }

                return results;
            }
            private IList<float> GetValues(int maxCount, Func<SvgTextBase, IEnumerable<SvgUnit>> listGetter, UnitRenderingType renderingType)
            {
                var currState = this;
                int charCount = 0;
                var results = new List<float>();
                int resultCount = 0;

                while (currState != null)
                {
                    charCount += currState.NumChars;
                    results.AddRange(listGetter.Invoke(currState.Element).Skip(charCount).Take(maxCount).Select(p => p.ToDeviceValue(currState.Renderer, renderingType, currState.Element)));
                    if (results.Count > resultCount)
                    {
                        maxCount -= results.Count - resultCount;
                        charCount += results.Count - resultCount;
                        resultCount = results.Count;
                    }

                    if (maxCount < 1) return results;

                    currState = currState.Parent;
                }

                return results;
            }
        }

933
934
935
936
937
        /// <summary>Empty text elements are not legal - only write this element if it has children.</summary>
        public override bool ShouldWriteElement()
        {
            return (this.HasChildren() || this.Nodes.Count > 0);
        }
938
939
    }
}