SvgTextBase.cs 21.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 enum XmlSpaceHandling
    {
        @default,
        preserve
    }
19

20
21
    public abstract class SvgTextBase : SvgVisualElement
    {
22
23
24
25
        private SvgUnitCollection _x = new SvgUnitCollection();
        private SvgUnitCollection _y = new SvgUnitCollection();
        private SvgUnitCollection _dy = new SvgUnitCollection();
        private SvgUnitCollection _dx = new SvgUnitCollection();
26
27
28
        private SvgUnit _letterSpacing;
        private SvgUnit _wordSpacing;
        private static readonly SvgRenderer _stringMeasure;
29
        
30
31
32
33
34
35
36
37
38
39
40
        private XmlSpaceHandling _space = XmlSpaceHandling.@default;

        /// <summary>
        /// Initializes the <see cref="SvgTextBase"/> class.
        /// </summary>
        static SvgTextBase()
        {
            Bitmap bitmap = new Bitmap(1, 1);
            _stringMeasure = SvgRenderer.FromImage(bitmap);
            _stringMeasure.TextRenderingHint = TextRenderingHint.AntiAlias;
        }
41

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        /// <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
        {
58
59
60
61
62
63
64
65
66
            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; }
67
68
69
70
71
72
73
        }

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

        /// <summary>
        /// Gets or sets the dX.
        /// </summary>
        /// <value>The dX.</value>
        [SvgAttribute("dx")]
93
        public virtual SvgUnitCollection Dx
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        {
            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")]
112
        public virtual SvgUnitCollection Y
113
        {
114
115
116
117
118
119
120
121
122
123
            get { return this._y; }
            set
            {
                if (_y != value)
                {
                    this._y = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "y", Value = value });
                }
            }
124
125
126
127
128
129
130
        }

        /// <summary>
        /// Gets or sets the dY.
        /// </summary>
        /// <value>The dY.</value>
        [SvgAttribute("dy")]
131
        public virtual SvgUnitCollection Dy
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
        {
            get { return this._dy; }
            set
            {
                if (_dy != value)
                {
                    this._dy = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "dy", Value = value });
                }
            }
        }

        /// <summary>
        /// Specifies spacing behavior between text characters.
        /// </summary>
        [SvgAttribute("letter-spacing")]
        public virtual SvgUnit LetterSpacing
        {
            get { return this._letterSpacing; }
            set { this._letterSpacing = value; this.IsPathDirty = true; }
        }

        /// <summary>
        /// Specifies spacing behavior between words.
        /// </summary>
        [SvgAttribute("word-spacing")]
        public virtual SvgUnit WordSpacing
        {
            get { return this._wordSpacing; }
            set { this._wordSpacing = value; this.IsPathDirty = true; }
        }

        /// <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
        {
174
            get { return (this.Attributes["fill"] == null) ? new SvgColourServer(System.Drawing.Color.Black) : (SvgPaintServer)this.Attributes["fill"]; }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            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>
        /// <value>The bounds.</value>
        public override System.Drawing.RectangleF Bounds
        {
204
205
            get 
            {
206
                var path = this.Path(null);
207
208
                foreach (var elem in this.Children.OfType<SvgVisualElement>())
                {
209
                    path.AddPath(elem.Path(null), false);
210
211
212
                }
                return path.GetBounds(); 
            }
213
214
215
216
217
218
219
220
221
        }

        /// <summary>
        /// Renders the <see cref="SvgElement"/> and contents to the specified <see cref="Graphics"/> object.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> object to render to.</param>
        /// <remarks>Necessary to make sure that any internal tspan elements get rendered as well</remarks>
        protected override void Render(SvgRenderer renderer)
        {
222
            if ((this.Path(renderer) != null) && this.Visible && this.Displayable)
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
            {
                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);
            }
        }

        private GraphicsPath _path;

        protected class NodeBounds
        {
            public float xOffset { get; set; }
            public SizeF Bounds { get; set; }
            public ISvgNode Node { get; set; }
        }
        protected class BoundsData
        {
            private List<NodeBounds> _nodes = new List<NodeBounds>();
259
            public IList<NodeBounds> Nodes
260
261
262
263
264
            {
                get { return _nodes; }
            }
            public SizeF Bounds { get; set; }
        }
265
        protected BoundsData GetTextBounds(SvgRenderer renderer)
266
        {
267
            var font = GetFont(renderer);
268
269
270
271
272
273
            SvgTextBase innerText;
            SizeF stringBounds;
            float totalHeight = 0;
            float totalWidth = 0;

            var result = new BoundsData();
274
            var nodes = (from n in this.Nodes
275
276
                         where (n is SvgContentNode || n is SvgTextBase) && !string.IsNullOrEmpty(n.Content)
                         select n).ToList();
277

278
279
280
281
282
283
284
            if (nodes.FirstOrDefault() is SvgContentNode && _x.Count > 1)
            {
                string ch;
                var content = nodes.First() as SvgContentNode;
                nodes.RemoveAt(0);
                int posCount = Math.Min(content.Content.Length, _x.Count);
                var text = PrepareText(content.Content, false, (nodes.Count > 1 && nodes[1] is SvgTextBase));
285

286
287
288
289
290
                for (var i = 0; i < posCount; i++)
                {
                    ch = (i == posCount - 1 ? text.Substring(i) : text.Substring(i, 1));
                    stringBounds = _stringMeasure.MeasureString(ch, font);
                    totalHeight = Math.Max(totalHeight, stringBounds.Height);
291
292
293
294
                    result.Nodes.Add(new NodeBounds()
                    {
                        Bounds = stringBounds,
                        Node = new SvgContentNode() { Content = ch },
295
296
                        xOffset = (i == 0 ? 0 : _x[i].ToDeviceValue(renderer, UnitRenderingType.Horizontal, this) -
                                                _x[0].ToDeviceValue(renderer, UnitRenderingType.Horizontal, this))
297
                    });
298
299
300
                }
            }

301
302
303
304
305
306
307
308
309
310
311
312
            ISvgNode node;
            for (var i = 0; i < nodes.Count; i++)
            {
                node = nodes[i];
                lock (_stringMeasure)
                {
                    innerText = node as SvgTextBase;
                    if (innerText == null)
                    {
                        stringBounds = _stringMeasure.MeasureString(PrepareText(node.Content,
                                                                                i > 0 && nodes[i - 1] is SvgTextBase,
                                                                                i < nodes.Count - 1 && nodes[i + 1] is SvgTextBase), font);
313
                        result.Nodes.Add(new NodeBounds() { Bounds = stringBounds, Node = node, xOffset = totalWidth });
314
315
316
                    }
                    else
                    {
317
                        stringBounds = innerText.GetTextBounds(renderer).Bounds;
318
                        result.Nodes.Add(new NodeBounds() { Bounds = stringBounds, Node = node, xOffset = totalWidth });
319
                        if (innerText.Dx.Count == 1) totalWidth += innerText.Dx[0].ToDeviceValue(renderer, UnitRenderingType.Horizontal, this);
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
                    }
                    totalHeight = Math.Max(totalHeight, stringBounds.Height);
                    totalWidth += stringBounds.Width;
                }
            }
            result.Bounds = new SizeF(totalWidth, totalHeight);
            return result;
        }

        protected float _calcX = 0;
        protected float _calcY = 0;

        /// <summary>
        /// Gets the <see cref="GraphicsPath"/> for this element.
        /// </summary>
        /// <value></value>
336
        public override System.Drawing.Drawing2D.GraphicsPath Path(SvgRenderer renderer)
337
        {
338
339
340
341
342
343
344
345
            // Make sure the path is always null if there is no text
            //if there is a TSpan inside of this text element then path should not be null (even if this text is empty!)
            if ((string.IsNullOrEmpty(this.Text) || this.Text.Trim().Length < 1) && this.Children.Where(x => x is SvgTextSpan).Select(x => x as SvgTextSpan).Count() == 0)
                return _path = null;
            //NOT SURE WHAT THIS IS ABOUT - Path gets created again anyway - WTF?
            // When an empty string is passed to GraphicsPath, it rises an InvalidArgumentException...

            if (_path == null || this.IsPathDirty)
346
            {
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
                renderer = (renderer ?? SvgRenderer.FromNull());
                // Measure the overall bounds of all the text
                var boundsData = GetTextBounds(renderer);

                var font = GetFont(renderer);
                SvgTextBase innerText;
                float x = (_x.Count < 1 ? _calcX : _x[0].ToDeviceValue(renderer, UnitRenderingType.HorizontalOffset, this)) +
                                                   (_dx.Count < 1 ? 0 : _dx[0].ToDeviceValue(renderer, UnitRenderingType.Horizontal, this));
                float y = (_y.Count < 1 ? _calcY : _y[0].ToDeviceValue(renderer, UnitRenderingType.VerticalOffset, this)) +
                                                   (_dy.Count < 1 ? 0 : _dy[0].ToDeviceValue(renderer, UnitRenderingType.Vertical, this));

                _path = new GraphicsPath();
                _path.StartFigure();

                // Determine the location of the start point
                switch (this.TextAnchor)
363
                {
364
365
366
367
368
369
370
                    case SvgTextAnchor.Middle:
                        x -= (boundsData.Bounds.Width / 2);
                        break;
                    case SvgTextAnchor.End:
                        x -= boundsData.Bounds.Width;
                        break;
                }
371

372
373
374
375
                try
                {
                    renderer.Boundable(new FontBoundable(font));
                    switch (this.BaselineShift)
376
                    {
377
378
379
380
381
382
383
384
                        case null:
                        case "":
                        case "baseline":
                        case "inherit":
                            // do nothing
                            break;
                        case "sub":
                            y += new SvgUnit(SvgUnitType.Ex, 1).ToDeviceValue(renderer, UnitRenderingType.Vertical, this);
385
                            break;
386
387
388
389
390
391
392
                        case "super":
                            y -= new SvgUnit(SvgUnitType.Ex, 1).ToDeviceValue(renderer, UnitRenderingType.Vertical, this);
                            break;
                        default:
                            var convert = new SvgUnitConverter();
                            var shift = (SvgUnit)convert.ConvertFromInvariantString(this.BaselineShift);
                            y -= shift.ToDeviceValue(renderer, UnitRenderingType.Vertical, this);
393
394
                            break;
                    }
395
396
397
398
399
                }
                finally
                {
                    renderer.PopBoundable();
                }
400

401
402
403
404
405
406
407
                NodeBounds data;
                var yCummOffset = 0.0f;
                for (var i = 0; i < boundsData.Nodes.Count; i++)
                {
                    data = boundsData.Nodes[i];
                    innerText = data.Node as SvgTextBase;
                    if (innerText == null)
408
                    {
409
410
411
412
413
414
415
416
417
418
                        // Minus FontSize because the x/y coords mark the bottom left, not bottom top.
                        DrawString(renderer, _path, x + data.xOffset, y - boundsData.Bounds.Height, font,
                                    PrepareText(data.Node.Content, i > 0 && boundsData.Nodes[i - 1].Node is SvgTextBase,
                                                                    i < boundsData.Nodes.Count - 1 && boundsData.Nodes[i + 1].Node is SvgTextBase));
                    }
                    else
                    {
                        innerText._calcX = x + data.xOffset;
                        innerText._calcY = y + yCummOffset;
                        if (innerText.Dy.Count == 1) yCummOffset += innerText.Dy[0].ToDeviceValue(renderer, UnitRenderingType.Vertical, this);
419
420
                    }
                }
421
422
423

                _path.CloseFigure();
                this.IsPathDirty = false;
424
            }
425
            return _path;
426
427
        }

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

430
431
432
433
434
435
436
437
438
        /// <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>
        protected string PrepareText(string value, bool leadingSpace, bool trailingSpace)
        {
            if (_space == XmlSpaceHandling.preserve)
            {
439
                return value.Replace('\t', ' ').Replace("\r\n", " ").Replace('\r', ' ').Replace('\n', ' ');
440
441
442
            }
            else
            {
443
444
445
446
                var convValue = MultipleSpaces.Replace(value.Replace("\r", "").Replace("\n", "").Replace('\t', ' '), " ");
                if (!leadingSpace) convValue = convValue.TrimStart();
                if (!trailingSpace) convValue = convValue.TrimEnd();
                return convValue;
447
448
449
450
451
452
            }
        }

        /// <summary>
        /// Draws a string on a path at a specified location and with a specified font.
        /// </summary>
453
        internal void DrawString(SvgRenderer renderer, GraphicsPath path, float x, float y, Font font, string text)
454
455
456
457
458
459
460
461
        {
            PointF location = new PointF(x, y);

            // No way to do letter-spacing or word-spacing, so do manually
            if (this.LetterSpacing.Value > 0.0f || this.WordSpacing.Value > 0.0f)
            {
                // Cut up into words, or just leave as required
                string[] words = (this.WordSpacing.Value > 0.0f) ? text.Split(' ') : new string[] { text };
462
463
                float wordSpacing = this.WordSpacing.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this);
                float letterSpacing = this.LetterSpacing.ToDeviceValue(renderer, UnitRenderingType.Horizontal, this);
464
465
466
467
468
469
470
471
472
473
                float start = x;

                foreach (string word in words)
                {
                    // Only do if there is line spacing, just write the word otherwise
                    if (this.LetterSpacing.Value > 0.0f)
                    {
                        char[] characters = word.ToCharArray();
                        foreach (char currentCharacter in characters)
                        {
474
                            path.AddString(currentCharacter.ToString(), font.FontFamily, (int)font.Style, font.Size, location, StringFormat.GenericTypographic);
475
476
477
478
479
                            location = new PointF(path.GetBounds().Width + start + letterSpacing, location.Y);
                        }
                    }
                    else
                    {
480
                        path.AddString(word, font.FontFamily, (int)font.Style, font.Size, location, StringFormat.GenericTypographic);
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
                    }

                    // Move the location of the word to be written along
                    location = new PointF(path.GetBounds().Width + start + wordSpacing, location.Y);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(text))
                {
                    path.AddString(text, font.FontFamily, (int)font.Style, font.Size, location, StringFormat.GenericTypographic);
                }
            }
        }

        [SvgAttribute("onchange")]
497
        public event EventHandler<StringArg> Change;
498
499

        //change
500
501
        protected void OnChange(string newString, string sessionID)
        {
502
            RaiseChange(this, new StringArg { s = newString, SessionID = sessionID });
503
        }
504

505
506
        protected void RaiseChange(object sender, StringArg s)
        {
507
            var handler = Change;
508
509
510
511
512
513
514
            if (handler != null)
            {
                handler(sender, s);
            }
        }

#if Net4
515
516
517
518
519
520
        public override void RegisterEvents(ISvgEventCaller caller)
        {
            //register basic events
            base.RegisterEvents(caller); 
            
            //add change event for text
521
            caller.RegisterAction<string, string>(this.ID + "/onchange", OnChange);
522
523
524
525
526
527
528
529
530
531
532
        }
        
        public override void UnregisterEvents(ISvgEventCaller caller)
        {
            //unregister base events
            base.UnregisterEvents(caller);
            
            //unregister change event
            caller.UnregisterAction(this.ID + "/onchange");
            
        }
533
#endif
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

        private class FontBoundable : ISvgBoundable
        {
            private Font _font;

            public FontBoundable(Font font)
            {
                _font = font;
            }

            public PointF Location
            {
                get { return PointF.Empty; }
            }

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

            public RectangleF Bounds
            {
                get { return new RectangleF(this.Location, this.Size); }
            }
        }
559
560
    }
}