SvgText.cs 16.6 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
3
using System;
using System.Collections.Generic;
using System.Text;
4
using System.Text.RegularExpressions;
davescriven's avatar
davescriven committed
5
6
7
8
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
9
10
using Svg.DataTypes;
using System.Linq;
davescriven's avatar
davescriven committed
11
12
13
14
15
16

namespace Svg
{
    /// <summary>
    /// The <see cref="SvgText"/> element defines a graphics element consisting of text.
    /// </summary>
17
    [SvgElement("text")]
18
    public class SvgText : SvgVisualElement
davescriven's avatar
davescriven committed
19
20
21
    {
        private SvgUnit _x;
        private SvgUnit _y;
22
23
        private SvgUnit _dy;
        private SvgUnit _dx;
davescriven's avatar
davescriven committed
24
25
        private SvgUnit _letterSpacing;
        private SvgUnit _wordSpacing;
26
27
28
29
        private SvgUnit _fontSize;
		private SvgFontWeight _fontWeight;
        private string _font;
        private string _fontFamily;
davescriven's avatar
davescriven committed
30
31
        private GraphicsPath _path;
        private SvgTextAnchor _textAnchor = SvgTextAnchor.Start;
32
        private static readonly SvgRenderer _stringMeasure;
samjudson's avatar
samjudson committed
33
34
        private const string DefaultFontFamily = "Times New Roman";

davescriven's avatar
davescriven committed
35
36
37
38
39
40
        /// <summary>
        /// Initializes the <see cref="SvgText"/> class.
        /// </summary>
        static SvgText()
        {
            Bitmap bitmap = new Bitmap(1, 1);
41
            _stringMeasure = SvgRenderer.FromImage(bitmap);
42
            _stringMeasure.TextRenderingHint = TextRenderingHint.AntiAlias;
davescriven's avatar
davescriven committed
43
44
45
46
47
48
49
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SvgText"/> class.
        /// </summary>
        public SvgText()
        {
50
51
            this._fontFamily = DefaultFontFamily;
            this._fontSize = new SvgUnit(0.0f);
52
53
            this._dy = new SvgUnit(0.0f);
            this._dx = new SvgUnit(0.0f);
davescriven's avatar
davescriven committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SvgText"/> class.
        /// </summary>
        /// <param name="text">The text.</param>
        public SvgText(string text) : this()
        {
            this.Text = text;
        }

        /// <summary>
        /// Gets or sets the text to be rendered.
        /// </summary>
        public virtual string Text
        {
            get { return base.Content; }
Tebjan Halm's avatar
Tebjan Halm committed
71
            set { base.Content = value; this.IsPathDirty = true; this.Content = value; }
davescriven's avatar
davescriven committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        }

        /// <summary>
        /// Gets or sets the text anchor.
        /// </summary>
        /// <value>The text anchor.</value>
        [SvgAttribute("text-anchor")]
        public virtual SvgTextAnchor TextAnchor
        {
            get { return this._textAnchor; }
            set { this._textAnchor = value; this.IsPathDirty = true; }
        }

        /// <summary>
        /// Gets or sets the X.
        /// </summary>
        /// <value>The X.</value>
        [SvgAttribute("x")]
        public virtual SvgUnit X
        {
92
93
94
95
96
97
98
99
100
101
        	get { return this._x; }
        	set
        	{
        		if(_x != value)
        		{
        			this._x = value;
        			this.IsPathDirty = true;
        			OnAttributeChanged(new AttributeEventArgs{ Attribute = "x", Value = value });
        		}
        	}
davescriven's avatar
davescriven committed
102
103
        }

104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
        /// <summary>
        /// Gets or sets the dX.
        /// </summary>
        /// <value>The dX.</value>
        [SvgAttribute("dx")]
        public virtual SvgUnit Dx
        {
            get { return this._dx; }
            set
            {
                if (_dx != value)
                {
                    this._dx = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "dx", Value = value });
                }
            }
        }

davescriven's avatar
davescriven committed
123
124
125
126
127
128
129
        /// <summary>
        /// Gets or sets the Y.
        /// </summary>
        /// <value>The Y.</value>
        [SvgAttribute("y")]
        public virtual SvgUnit Y
        {
130
131
132
133
134
135
136
137
138
139
        	get { return this._y; }
        	set
        	{
        		if(_y != value)
        		{
        			this._y = value;
        			this.IsPathDirty = true;
        			OnAttributeChanged(new AttributeEventArgs{ Attribute = "y", Value = value });
        		}
        	}
davescriven's avatar
davescriven committed
140
141
        }

142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
        /// <summary>
        /// Gets or sets the dY.
        /// </summary>
        /// <value>The dY.</value>
        [SvgAttribute("dy")]
        public virtual SvgUnit Dy
        {
            get { return this._dy; }
            set
            {
                if (_dy != value)
                {
                    this._dy = value;
                    this.IsPathDirty = true;
                    OnAttributeChanged(new AttributeEventArgs { Attribute = "dy", Value = value });
                }
            }
        }

davescriven's avatar
davescriven committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
        /// <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>
        /// Indicates which font family is to be used to render the text.
        /// </summary>
        [SvgAttribute("font-family")]
Tebjan Halm's avatar
Tebjan Halm committed
185
        public virtual string FontFamily
davescriven's avatar
davescriven committed
186
        {
187
188
189
190
191
192
            get { return this._fontFamily; }
            set
            {
                this._fontFamily = ValidateFontFamily(value);
                this.IsPathDirty = true;
            }
davescriven's avatar
davescriven committed
193
194
195
196
197
198
199
200
        }

        /// <summary>
        /// Refers to the size of the font from baseline to baseline when multiple lines of text are set solid in a multiline layout environment.
        /// </summary>
        [SvgAttribute("font-size")]
        public virtual SvgUnit FontSize
        {
201
202
            get { return this._fontSize; }
            set { this._fontSize = value; this.IsPathDirty = true; }
davescriven's avatar
davescriven committed
203
204
        }

205
206
207
208
209
210
211

		/// <summary>
		/// Refers to the boldness of the font.
		/// </summary>
		[SvgAttribute("font-weight")]
		public virtual SvgFontWeight FontWeight
		{
212
213
			get { return this._fontWeight; }
			set { this._fontWeight = value; this.IsPathDirty = true; }
214
215
216
		}


davescriven's avatar
davescriven committed
217
218
219
220
        /// <summary>
        /// Set all font information.
        /// </summary>
        [SvgAttribute("font")]
Tebjan Halm's avatar
Tebjan Halm committed
221
        public virtual string Font
davescriven's avatar
davescriven committed
222
        {
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
            get { return this._font; }
            set
            {
                var parts = value.Split(',');
                foreach (var part in parts)
                {
                    //This deals with setting font size. Looks for either <number>px or <number>pt style="font: bold 16px/normal 'trebuchet ms', verdana, sans-serif;"
                    Regex rx = new Regex(@"(\d+)+(?=pt|px)");
                    var res = rx.Match(part);
                    if (res.Success)
                    {
                        int fontSize = 10;
                        int.TryParse(res.Value, out fontSize);
                        this.FontSize = new SvgUnit((float)fontSize);
                    }

                    //this assumes "bold" has spaces around it. e.g.: style="font: bold 16px/normal 
                    rx = new Regex(@"\sbold\s");
                    res = rx.Match(part);
                    if (res.Success)
                    {
                        this.FontWeight = SvgFontWeight.bold;
                    }
                }
                var font = ValidateFontFamily(value);
                this._fontFamily = font;
                this._font = font; //not sure this is used?

                this.IsPathDirty = true;
            }
davescriven's avatar
davescriven committed
253
254
255
256
257
258
259
260
261
262
263
        }

        /// <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
        {
264
            get { return (this.Attributes["fill"] == null) ? new SvgColourServer(Color.Black) : (SvgPaintServer)this.Attributes["fill"]; }
265
            set { this.Attributes["fill"] = value; }
davescriven's avatar
davescriven committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
        }

        /// <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
        {
            get { return this.Path.GetBounds(); }
        }

Tebjan Halm's avatar
Tebjan Halm committed
297
        static private RectangleF MeasureString(SvgRenderer renderer, string text, Font font)
298
299
300
        {
            GraphicsPath p = new GraphicsPath();
            p.AddString(text, font.FontFamily, 0, font.Size, new PointF(0.0f, 0.0f), StringFormat.GenericTypographic);
301
            
302
            p.Transform(renderer.Transform);
Tebjan Halm's avatar
Tebjan Halm committed
303
            return p.GetBounds();
304
305
        }

davescriven's avatar
davescriven committed
306
307
308
309
310
311
312
313
314
        /// <summary>
        /// Gets the <see cref="GraphicsPath"/> for this element.
        /// </summary>
        /// <value></value>
        public override System.Drawing.Drawing2D.GraphicsPath Path
        {
            get
            {
                // Make sure the path is always null if there is no text
Mark Johnson's avatar
Mark Johnson committed
315
				//if there is a TSpan inside of this text element then path should not be null (even if this text is empty!)
316
				if (string.IsNullOrWhiteSpace(this.Text) && this.Children.Where(x => x is SvgTextSpan).Select(x => x as SvgTextSpan).Count() == 0)
317
				    return _path = null;
318
				//NOT SURE WHAT THIS IS ABOUT - Path gets created again anyway - WTF?
319
                // When an empty string is passed to GraphicsPath, it rises an InvalidArgumentException...
320
321

				if (_path == null || this.IsPathDirty)
davescriven's avatar
davescriven committed
322
                {
323
324
325
326
327
328
329
330
                    float fontSize = this.FontSize.ToDeviceValue(this);
                    if (fontSize == 0.0f)
                    {
                        fontSize = 1.0f;
                    }

                	FontStyle fontWeight = (this.FontWeight == SvgFontWeight.bold ? FontStyle.Bold : FontStyle.Regular);
					Font font = new Font(this._fontFamily, fontSize, fontWeight, GraphicsUnit.Pixel);
davescriven's avatar
davescriven committed
331
332
333
334

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

335
					if (!string.IsNullOrEmpty(this.Text))
336
	                	DrawString(_path, this.X, this.Y, this.Dx, this.Dy, font, fontSize, this.Text);
davescriven's avatar
davescriven committed
337

338
339
					foreach (var tspan in this.Children.Where(x => x is SvgTextSpan).Select(x => x as SvgTextSpan))
					{
340
341
342
343
344
345
346
347
348
349
						if (!string.IsNullOrEmpty(tspan.Text))
							DrawString(
							_path, 
							tspan.X == SvgUnit.Empty ? this.X: tspan.X,
							tspan.Y == SvgUnit.Empty ? this.Y : tspan.Y, 
							tspan.DX,
							tspan.DY,
							font, 
							fontSize,
							tspan.Text);
350
351
352
					}

                	_path.CloseFigure();
davescriven's avatar
davescriven committed
353
354
355
356
                    this.IsPathDirty = false;
                }
                return _path;
            }
357
358
359
360
            protected set
            {
                _path = value;
            }
davescriven's avatar
davescriven committed
361
        }
362

samjudson's avatar
samjudson committed
363
364
365
        private static string ValidateFontFamily(string fontFamilyList)
        {
            // Split font family list on "," and then trim start and end spaces and quotes.
366
            var fontParts = fontFamilyList.Split(new[] { ',' }).Select(fontName => fontName.Trim(new[] { '"', ' ','\''  }));
samjudson's avatar
samjudson committed
367
368
369
370

            var families = System.Drawing.FontFamily.Families;

            // Find a the first font that exists in the list of installed font families.
371
372
            //styles from IE get sent through as lowercase.
            foreach (var f in fontParts.Where(f => families.Any(family => family.Name.ToLower() == f.ToLower())))
samjudson's avatar
samjudson committed
373
374
375
376
377
378
            {
                return f;
            }
            // No valid font family found from the list requested.
            return DefaultFontFamily;
        }
379

380
		private void DrawString(GraphicsPath path, SvgUnit x, SvgUnit y, SvgUnit dx, SvgUnit dy, Font font, float fontSize, string text)
381
		{
382
			PointF location = PointF.Empty;
383
384
385
386
387
388
			SizeF stringBounds;

			lock (_stringMeasure)
			{
				stringBounds = _stringMeasure.MeasureString(text, font);
			}
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423

			float xToDevice = x.ToDeviceValue(this) + dx.ToDeviceValue(this);
			float yToDevice = y.ToDeviceValue(this, true) + dy.ToDeviceValue(this, true);

			// Minus FontSize because the x/y coords mark the bottom left, not bottom top.
			switch (this.TextAnchor)
			{
				case SvgTextAnchor.Start:
					location = new PointF(xToDevice, yToDevice - stringBounds.Height);
					break;
				case SvgTextAnchor.Middle:
					location = new PointF(xToDevice - (stringBounds.Width / 2), yToDevice - stringBounds.Height);
					break;
				case SvgTextAnchor.End:
					location = new PointF(xToDevice - stringBounds.Width, yToDevice - stringBounds.Height);
					break;
			}

			// 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 };
				float wordSpacing = this.WordSpacing.ToDeviceValue(this);
				float letterSpacing = this.LetterSpacing.ToDeviceValue(this);
				float start = this.X.ToDeviceValue(this);

				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)
						{
424
							path.AddString(currentCharacter.ToString(), new FontFamily(this._fontFamily), (int)font.Style, fontSize, location, StringFormat.GenericTypographic);
425
426
427
428
429
							location = new PointF(path.GetBounds().Width + start + letterSpacing, location.Y);
						}
					}
					else
					{
430
						path.AddString(word, new FontFamily(this._fontFamily), (int)font.Style, fontSize, location, StringFormat.GenericTypographic);
431
432
433
434
435
436
437
438
439
440
					}

					// 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))
				{
441
					path.AddString(text, new FontFamily(this._fontFamily), (int)font.Style, fontSize, location, StringFormat.GenericTypographic);
442
443
444
445
				}
			}

		}
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
		
		[SvgAttribute("onchange")]
        public event EventHandler<StringArg> Change;
		
		//change
        protected void OnChange(string newString, string sessionID)
        {
        	RaiseChange(this, new StringArg {s = newString, SessionID = sessionID});
        }
        
        protected void RaiseChange(object sender, StringArg s)
        {
        	var handler = Change;
            if (handler != null)
            {
                handler(sender, s);
            }
        }
464

465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
		public override void RegisterEvents(ISvgEventCaller caller)
		{
			//register basic events
			base.RegisterEvents(caller); 
			
			//add change event for text
            caller.RegisterAction<string, string>(this.ID + "/onchange", OnChange);
		}
		
		public override void UnregisterEvents(ISvgEventCaller caller)
		{
			//unregister base events
			base.UnregisterEvents(caller);
			
			//unregister change event
        	caller.UnregisterAction(this.ID + "/onchange");
			
		}
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502

		public override SvgElement DeepCopy()
		{
			return DeepCopy<SvgText>();
		}

		public override SvgElement DeepCopy<T>()
		{
			var newObj = base.DeepCopy<T>() as SvgText;
			newObj.TextAnchor = this.TextAnchor;
			newObj.WordSpacing = this.WordSpacing;
			newObj.LetterSpacing = this.LetterSpacing;
			newObj.Font = this.Font;
			newObj.FontFamily = this.FontFamily;
			newObj.FontSize = this.FontSize;
			newObj.FontWeight = this.FontWeight;
			newObj.X = this.X;
			newObj.Y = this.Y;
			return newObj;
		}
davescriven's avatar
davescriven committed
503
    }
samjudson's avatar
samjudson committed
504
}