SvgTextBase.cs 36.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;

namespace Svg
{
    public abstract class SvgTextBase : SvgVisualElement
    {
Eric Domke's avatar
Eric Domke committed
16
17
18
19
20
21
        protected SvgUnitCollection _x = new SvgUnitCollection();
        protected SvgUnitCollection _y = new SvgUnitCollection();
        protected SvgUnitCollection _dy = new SvgUnitCollection();
        protected SvgUnitCollection _dx = new SvgUnitCollection();
        private string _rotate;
        private List<float> _rotations = new List<float>();
22
        
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
        /// <summary>
        /// Gets or sets the text to be rendered.
        /// </summary>
        public virtual string Text
        {
            get { return base.Content; }
            set { base.Content = value; this.IsPathDirty = true; this.Content = value; }
        }

        /// <summary>
        /// Gets or sets the text anchor.
        /// </summary>
        /// <value>The text anchor.</value>
        [SvgAttribute("text-anchor")]
        public virtual SvgTextAnchor TextAnchor
        {
39
40
41
42
43
44
45
46
47
            get { return (this.Attributes["text-anchor"] == null) ? SvgTextAnchor.inherit : (SvgTextAnchor)this.Attributes["text-anchor"]; }
            set { this.Attributes["text-anchor"] = value; this.IsPathDirty = true; }
        }

        [SvgAttribute("baseline-shift")]
        public virtual string BaselineShift
        {
            get { return this.Attributes["baseline-shift"] as string; }
            set { this.Attributes["baseline-shift"] = value; this.IsPathDirty = true; }
48
49
        }

Eric Domke's avatar
Eric Domke committed
50
51
52
53
54
55
        public override XmlSpaceHandling SpaceHandling
        {
            get { return base.SpaceHandling; }
            set { base.SpaceHandling = value; this.IsPathDirty = true; }
        }

56
57
58
59
60
        /// <summary>
        /// Gets or sets the X.
        /// </summary>
        /// <value>The X.</value>
        [SvgAttribute("x")]
61
        public virtual SvgUnitCollection X
62
        {
63
64
65
66
67
68
69
70
71
72
            get { return this._x; }
            set
            {
                if (_x != value)
                {
                    this._x = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "x", Value = value });
                }
            }
73
74
75
76
77
78
79
        }

        /// <summary>
        /// Gets or sets the dX.
        /// </summary>
        /// <value>The dX.</value>
        [SvgAttribute("dx")]
80
        public virtual SvgUnitCollection Dx
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
        {
            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")]
99
        public virtual SvgUnitCollection Y
100
        {
101
102
103
104
105
106
107
108
109
110
            get { return this._y; }
            set
            {
                if (_y != value)
                {
                    this._y = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "y", Value = value });
                }
            }
111
112
113
114
115
116
117
        }

        /// <summary>
        /// Gets or sets the dY.
        /// </summary>
        /// <value>The dY.</value>
        [SvgAttribute("dy")]
118
        public virtual SvgUnitCollection Dy
119
120
121
122
123
124
125
126
127
128
129
130
131
        {
            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
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
        /// <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();
                    this._rotations.AddRange(from r in _rotate.Split(new char[] {',', ' ', '\r', '\n', '\t'}, StringSplitOptions.RemoveEmptyEntries) select float.Parse(r));
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "rotate", Value = value });
                }
            }
        }

        /// <summary>
        /// The pre-calculated length of the text
        /// </summary>
        [SvgAttribute("textLength")]
        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>
        [SvgAttribute("lengthAdjust")]
        public virtual SvgTextLengthAdjust LengthAdjust
        {
            get { return (this.Attributes["lengthAdjust"] == null) ? SvgTextLengthAdjust.spacing : (SvgTextLengthAdjust)this.Attributes["lengthAdjust"]; }
            set { this.Attributes["lengthAdjust"] = value; this.IsPathDirty = true; }
        }

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

        /// <summary>
        /// Specifies spacing behavior between words.
        /// </summary>
        [SvgAttribute("word-spacing")]
        public virtual SvgUnit WordSpacing
        {
Eric Domke's avatar
Eric Domke committed
190
191
            get { return (this.Attributes["word-spacing"] == null ? SvgUnit.None : (SvgUnit)this.Attributes["word-spacing"]); }
            set { this.Attributes["word-spacing"] = value; this.IsPathDirty = true; }
192
193
194
195
196
197
198
199
200
201
202
        }

        /// <summary>
        /// Gets or sets the fill.
        /// </summary>
        /// <remarks>
        /// <para>Unlike other <see cref="SvgGraphicsElement"/>s, <see cref="SvgText"/> has a default fill of black rather than transparent.</para>
        /// </remarks>
        /// <value>The fill.</value>
        public override SvgPaintServer Fill
        {
203
            get { return (this.Attributes["fill"] == null) ? new SvgColourServer(System.Drawing.Color.Black) : (SvgPaintServer)this.Attributes["fill"]; }
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
            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 or sets a value to determine if anti-aliasing should occur when the element is being rendered.
        /// </summary>
        /// <value></value>
        protected override bool RequiresSmoothRendering
        {
            get { return true; }
        }

        /// <summary>
        /// Gets the bounds of the element.
        /// </summary>
Dan Backes's avatar
Dan Backes committed
230
231
        /// <returns>The bounds.</returns>
        public override RectangleF CalculateBounds()
232
        {
Dan Backes's avatar
Dan Backes committed
233
234
            var path = this.Path(null);
            foreach (var elem in this.Children.OfType<SvgVisualElement>())
235
            {
Dan Backes's avatar
Dan Backes committed
236
                path.AddPath(elem.Path(null), false);
237
            }
Dan Backes's avatar
Dan Backes committed
238
            return path.GetBounds();
239
240
241
242
243
        }

        /// <summary>
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object.
        /// </summary>
Eric Domke's avatar
Eric Domke committed
244
        /// <param name="renderer">The <see cref="ISvgRenderer"/> object to render to.</param>
245
        /// <remarks>Necessary to make sure that any internal tspan elements get rendered as well</remarks>
Eric Domke's avatar
Eric Domke committed
246
        protected override void Render(ISvgRenderer renderer)
247
        {
248
            if ((this.Path(renderer) != null) && this.Visible && this.Displayable)
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
            {
                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
274
        internal virtual IEnumerable<ISvgNode> GetContentNodes()
275
        {
Eric Domke's avatar
Eric Domke committed
276
            return (this.Nodes == null || this.Nodes.Count < 1 ? this.Children.OfType<ISvgNode>() : this.Nodes);
277
        }
Eric Domke's avatar
Eric Domke committed
278
        protected virtual GraphicsPath GetBaselinePath(ISvgRenderer renderer)
279
        {
Eric Domke's avatar
Eric Domke committed
280
            return null;
281
        }
Eric Domke's avatar
Eric Domke committed
282
        protected virtual float GetAuthorPathLength()
283
        {
Eric Domke's avatar
Eric Domke committed
284
            return 0;
285
286
        }

Eric Domke's avatar
Eric Domke committed
287
        private GraphicsPath _path;
288
289
290
291
292

        /// <summary>
        /// Gets the <see cref="GraphicsPath"/> for this element.
        /// </summary>
        /// <value></value>
Ritch Melton's avatar
Ritch Melton committed
293
        public override GraphicsPath Path(ISvgRenderer renderer)
294
        {
295
            //if there is a TSpan inside of this text element then path should not be null (even if this text is empty!)
Ritch Melton's avatar
Ritch Melton committed
296
297
            var nodes = GetContentNodes().Where(x => x is SvgContentNode && 
                                                     string.IsNullOrEmpty(x.Content.Trim(new[] {'\r', '\n', '\t'})));
Eric Domke's avatar
Eric Domke committed
298
            
Ritch Melton's avatar
Ritch Melton committed
299
            if (_path == null || IsPathDirty || nodes.Count() == 1)
300
            {
301
                renderer = (renderer ?? SvgRenderer.FromNull());
Ritch Melton's avatar
Ritch Melton committed
302
                SetPath(new TextDrawingState(renderer, this));
Eric Domke's avatar
Eric Domke committed
303
304
305
            }
            return _path;
        }
306

Eric Domke's avatar
Eric Domke committed
307
308
309
310
        private void SetPath(TextDrawingState state)
        {
            SetPath(state, true);
        }
311

Eric Domke's avatar
Eric Domke committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
        /// <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>
        private void SetPath(TextDrawingState state, bool doMeasurements)
        {
            SvgTextBase inner;
            TextDrawingState newState;
            TextDrawingState origState = null;
            bool alignOnBaseline = state.BaselinePath != null && (this.TextAnchor == SvgTextAnchor.Middle || this.TextAnchor == SvgTextAnchor.End);
            if (doMeasurements)
            {
                if (this.TextLength != SvgUnit.None)
                {
                    origState = state.Clone();
                }
                else if (alignOnBaseline)
330
                {
Eric Domke's avatar
Eric Domke committed
331
332
                    origState = state.Clone();
                    state.BaselinePath = null;
333
                }
Eric Domke's avatar
Eric Domke committed
334
            }
335

Eric Domke's avatar
Eric Domke committed
336
337
338
339
            foreach (var node in GetContentNodes())
            {
                inner = node as SvgTextBase;
                if (inner == null)
340
                {
Eric Domke's avatar
Eric Domke committed
341
                    if (!string.IsNullOrEmpty(node.Content)) state.DrawString(PrepareText(node.Content));
342
                }
Eric Domke's avatar
Eric Domke committed
343
                else
344
                {
Eric Domke's avatar
Eric Domke committed
345
346
347
348
                    newState = new TextDrawingState(state, inner);
                    inner.SetPath(newState);
                    state.NumChars += newState.NumChars;
                    state.Current = newState.Current;
349
                }
Eric Domke's avatar
Eric Domke committed
350
            }
351

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

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


            _path = path;
            this.IsPathDirty = false;
402
403
        }

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

406
407
408
409
410
        /// <summary>
        /// Prepare the text according to the whitespace handling rules.  <see href="http://www.w3.org/TR/SVG/text.html">SVG Spec</see>.
        /// </summary>
        /// <param name="value">Text to be prepared</param>
        /// <returns>Prepared text</returns>
Eric Domke's avatar
Eric Domke committed
411
        protected string PrepareText(string value)
412
        {
Eric Domke's avatar
Eric Domke committed
413
            if (this.SpaceHandling == XmlSpaceHandling.preserve)
414
            {
415
                return value.Replace('\t', ' ').Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
416
417
418
            }
            else
            {
419
420
                var convValue = MultipleSpaces.Replace(value.Replace("\r", "").Replace("\n", "").Replace('\t', ' '), " ");
                return convValue;
421
422
423
            }
        }

424
        [SvgAttribute("onchange")]
425
        public event EventHandler<StringArg> Change;
426
427

        //change
428
429
        protected void OnChange(string newString, string sessionID)
        {
430
            RaiseChange(this, new StringArg { s = newString, SessionID = sessionID });
431
        }
432

433
434
        protected void RaiseChange(object sender, StringArg s)
        {
435
            var handler = Change;
436
437
438
439
440
441
            if (handler != null)
            {
                handler(sender, s);
            }
        }

Eric Domke's avatar
Eric Domke committed
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458


        //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();
        //}

459
#if Net4
460
461
462
463
464
465
        public override void RegisterEvents(ISvgEventCaller caller)
        {
            //register basic events
            base.RegisterEvents(caller); 
            
            //add change event for text
466
            caller.RegisterAction<string, string>(this.ID + "/onchange", OnChange);
467
468
469
470
471
472
473
474
475
476
477
        }
        
        public override void UnregisterEvents(ISvgEventCaller caller)
        {
            //unregister base events
            base.UnregisterEvents(caller);
            
            //unregister change event
            caller.UnregisterAction(this.ID + "/onchange");
            
        }
478
#endif
479
480
481

        private class FontBoundable : ISvgBoundable
        {
Eric Domke's avatar
Eric Domke committed
482
483
            private IFontDefn _font;
            private float _width = 1;
484

Eric Domke's avatar
Eric Domke committed
485
            public FontBoundable(IFontDefn font)
486
487
488
            {
                _font = font;
            }
Eric Domke's avatar
Eric Domke committed
489
            public FontBoundable(IFontDefn font, float width)
490
491
            {
                _font = font;
Eric Domke's avatar
Eric Domke committed
492
                _width = width;
493
494
            }

Dan Backes's avatar
Dan Backes committed
495
            public RectangleF CalculateBounds()
496
            {
Dan Backes's avatar
Dan Backes committed
497
                return new RectangleF(PointF.Empty, new SizeF(_width, _font.Size));
498
499
            }
        }
Eric Domke's avatar
Eric Domke committed
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

        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; }
            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;
                _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;
                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;
                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
564
                using (var font = this.Element.GetFont(this.Renderer))
Eric Domke's avatar
Eric Domke committed
565
                {
Eric Domke's avatar
Eric Domke committed
566
567
568
569
                    var fontBaselineHeight = font.Ascent(this.Renderer);
                    PathStatistics pathStats = null;
                    var pathScale = 1.0;
                    if (BaselinePath != null)
Eric Domke's avatar
Eric Domke committed
570
                    {
Eric Domke's avatar
Eric Domke committed
571
572
                        pathStats = new PathStatistics(BaselinePath.PathData);
                        if (_authorPathLength > 0) pathScale = _authorPathLength / pathStats.TotalLength;
Eric Domke's avatar
Eric Domke committed
573
574
                    }

Eric Domke's avatar
Eric Domke committed
575
576
577
578
579
580
581
                    // 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
582
                    {
Eric Domke's avatar
Eric Domke committed
583
584
585
586
                        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
587
                        {
Eric Domke's avatar
Eric Domke committed
588
                            if (xOffsets.Count < 1)
Eric Domke's avatar
Eric Domke committed
589
                            {
Eric Domke's avatar
Eric Domke committed
590
                                xOffsets.Add(StartOffsetAdjust);
Eric Domke's avatar
Eric Domke committed
591
592
593
                            }
                            else
                            {
Eric Domke's avatar
Eric Domke committed
594
                                xOffsets[0] += StartOffsetAdjust;
Eric Domke's avatar
Eric Domke committed
595
596
597
                            }
                        }

Eric Domke's avatar
Eric Domke committed
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
                        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
615

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

Eric Domke's avatar
Eric Domke committed
618
619
                        // 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
620

Eric Domke's avatar
Eric Domke committed
621
                        switch (baselineShiftText)
Eric Domke's avatar
Eric Domke committed
622
                        {
Eric Domke's avatar
Eric Domke committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
                            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
640
                        }
Eric Domke's avatar
Eric Domke committed
641
642

                        if (baselineShift != 0.0f)
Eric Domke's avatar
Eric Domke committed
643
                        {
Eric Domke's avatar
Eric Domke committed
644
645
646
647
648
649
650
651
                            if (yOffsets.Any())
                            {
                                yOffsets[0] += baselineShift;
                            }
                            else
                            {
                                yOffsets.Add(baselineShift);
                            }
Eric Domke's avatar
Eric Domke committed
652
653
                        }
                    }
Eric Domke's avatar
Eric Domke committed
654
655
656
657
                    finally
                    {
                        this.Renderer.PopBoundable();
                    }
Eric Domke's avatar
Eric Domke committed
658

Eric Domke's avatar
Eric Domke committed
659
660
661
662
663
664
665
666
667
                    // 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
668

Eric Domke's avatar
Eric Domke committed
669
670
671
                        DrawStringOnCurrPath(value[i].ToString(), font, new PointF(_xAnchor, yPos),
                                             fontBaselineHeight, (rotations.Count > i ? rotations[i] : rotations.LastOrDefault()));
                    }
Eric Domke's avatar
Eric Domke committed
672

Eric Domke's avatar
Eric Domke committed
673
674
675
676
677
678
679
680
681
682
683
                    // 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
684
685


Eric Domke's avatar
Eric Domke committed
686
687
688
689
                    // 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
690
                    {
Eric Domke's avatar
Eric Domke committed
691
692
693
694
695
                        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
696
                        {
Eric Domke's avatar
Eric Domke committed
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
                            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)
                            {
                                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)));
                                    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
722
723
724
                        }
                        else
                        {
Eric Domke's avatar
Eric Domke committed
725
                            xPos += charBounds.Last().Width;
Eric Domke's avatar
Eric Domke committed
726
727
728
                        }
                    }

Eric Domke's avatar
Eric Domke committed
729
730
                    // Render the string normally
                    if (lastIndividualChar < value.Length)
Eric Domke's avatar
Eric Domke committed
731
                    {
Eric Domke's avatar
Eric Domke committed
732
733
734
735
736
737
738
                        xPos += (xOffsets.Count > lastIndividualChar ? xOffsets[lastIndividualChar] : 0);
                        yPos = (yAnchors.Count > lastIndividualChar ? yAnchors[lastIndividualChar] : yPos) +
                                (yOffsets.Count > lastIndividualChar ? yOffsets[lastIndividualChar] : 0);
                        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
739
740
741
                    }


Eric Domke's avatar
Eric Domke committed
742
743
744
745
                    NumChars += value.Length;
                    // Undo any baseline shift.  This is not persisted, unlike normal vertical offsets.
                    this.Current = new PointF(xPos, yPos - baselineShift);
                }
Eric Domke's avatar
Eric Domke committed
746
747
748
749
750
751
752
753
754
            }

            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
755
756
757
758
759
760
761
762
                    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
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
                }

            }

            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
810
                        var xOffset = 0f; //_xAnchor - minX;
Eric Domke's avatar
Eric Domke committed
811
812
813
814
815
816
817
818
819
820
821
822
                        switch (Element.TextAnchor)
                        {
                            case SvgTextAnchor.Middle:
                                xOffset -= (maxX - minX) / 2;
                                break;
                            case SvgTextAnchor.End:
                                xOffset -= (maxX - minX);
                                break;
                        }

                        if (xOffset != 0)
                        {
Eric Domke's avatar
Eric Domke committed
823
                            using (var matrix = new Matrix())
Eric Domke's avatar
Eric Domke committed
824
                            {
Eric Domke's avatar
Eric Domke committed
825
826
827
828
829
                                matrix.Translate(xOffset, 0);
                                foreach (var path in _anchoredPaths)
                                {
                                    path.Transform(matrix);
                                }
Eric Domke's avatar
Eric Domke committed
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
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
                            }
                        }

                        _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;
            }
        }

903
904
    }
}