-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumericWithUnit.cs
558 lines (471 loc) · 19.3 KB
/
NumericWithUnit.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Windows.Forms.Design;
using System.Globalization;
using System.Reflection;
namespace NumericUnit
{
[Description("A text box that accepts numeric input followed by a character string. Together these are interpreted as a number and a unit (one of the units of the AllowedUnits collection)")]
public partial class NumericWithUnit : TextBox
{
//internal class AllowedUnitsCollectionEditor : CollectionEditor
//{
// public AllowedUnitsCollectionEditor(Type type) : base(type) { }
// public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
// {
// object result = base.EditValue(context, provider, value);
// // assign the temporary collection from the UI to the property
// ((NumericWithUnit)context.Instance).AllowedUnits = (ObservableCollection<Unit>)result;
// return result;
// }
//}
internal class UnitConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(InstanceDescriptor) || base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor) && value is Unit)
{
ConstructorInfo constructor = typeof(Unit).GetConstructor(new[] { typeof(string), typeof(double) });
var filter = value as Unit;
var descriptor = new InstanceDescriptor(constructor, new object[] { filter.UnitString, filter.UnitValue }, true);
return descriptor;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
[Serializable]
/// <summary>
/// A description of a Unit
/// </summary>
public class Unit
{
public string UnitString { get; set; }
public double UnitValue { get; set; }
/// <summary>
/// Creates a Unit which represents the value 1 (no unit).
/// </summary>
public Unit() { UnitString = ""; UnitValue = 1; }
/// <summary>
/// Creates a Unit which represents a value.
/// </summary>
/// <param name="unitString">The unit string ("milliseconds", "kilograms"...).</param>
/// <param name="unitValue">The value of the unit in base units (if working in SI units, "milliseconds" would have the value 0.001).</param>
public Unit(string unitString, double unitValue)
{
UnitString = unitString;
UnitValue = unitValue;
}
}
[Description("A collection of allowed units.")]
//[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Editor(typeof(CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[TypeConverter(typeof(UnitConverter))]
/// <summary>
/// A collection of allowed units.
/// </summary>
public ObservableCollection<Unit> AllowedUnits { get; set; }
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor(typeof(CollectionEditor), typeof(System.Drawing.Design.UITypeEditor))]
[TypeConverter(typeof(UnitConverter))]
public List<Unit> TestUnits { get; set; }
private bool forbiddenKey = false;
private bool enterKey = false;
private bool internalSet = false;
private Regex formatRegex;
private string unitsRegexString = "()$";
private string numberRegexString = @"^\s*[-+]?[0-9]+\.?[0-9]*([eE][-+]?[0-9]+)?\s*";
//private string numberRegexString = @"[+-]?[0-9]+\.?[0-9]*\s*";
[Description("The Maximum (unitless) value allowed to be entered.")]
[Category("Data")]
/// <summary>
/// The Maximum (unitless) value allowed to be entered.
/// </summary>
public double Maximum { get; set; }
[Description("The Minimum (unitless) value allowed to be entered.")]
[Category("Data")]
/// <summary>
/// The Minimum (unitless) value allowed to be entered.
/// </summary>
public double Minimum { get; set; }
private double value;
[Description("The current (unitless) value.")]
[Category("Appearance")]
/// <summary>
/// The current (unitless) value.
/// </summary>
public double Value
{
get { return value; }
set
{
// try to set it, throw exceptions if error
// these are caught but allow the debugger to catch them if set up in Visual Studio
try
{
// check range
if (value > Maximum) throw new ArgumentOutOfRangeException("Value", "Tried to set 'Value' to above 'Maximum'.");
if (value < Minimum) throw new ArgumentOutOfRangeException("Value", "Tried to set 'Value' to below 'Minimum'.");
this.value = value;
// set the text as well
// set flag not to change colour
internalSet = true;
Text = makeString(this.value);
internalSet = false;
}
catch (ArgumentOutOfRangeException ex)
{
// do nothing with it
}
}
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Description("The text shown.")]
[Category("Appearance")]
/// <summary>
/// Gets or sets the current text in the NumericWithUnit.
/// </summary>
public override string Text
{
get
{
return base.Text;
}
set
{
base.Text = value;
}
}
[Description("The number of decimal round the value up to.")]
[Category("Data")]
/// <summary>
/// How many Decimal places to allow, relative to SI unit! e.g. if DecimalPlaces = 3, then 1ms is allowed, but 0.1 ms isn't
/// </summary>
public int DecimalPlaces { get; set; }
[Description("The format string used to generate the UI Text. Must be a valid format string for the arguments {0} being the double value, and {1} being a the unit string.")]
[Category("Data")]
/// <summary>
/// The format string used to generate the UI Text. Must be a valid format string for the arguments {0} being the double value, and {1} being a the unit string.
/// </summary>
public string DisplayFormat
{
get { return _displayFormat; }
set
{
// test the display format to make sure it is correct
// just try to format something simple
try
{
if (value != null) String.Format(value, 0, "V");
// we got this far, so format should be ok!
_displayFormat = value;
}
catch (FormatException ex)
{
// don't do anything with it
}
}
}
private string _displayFormat;
[Description("The color that the background is set to when a correct value is entered, before pressing enter.")]
[Category("Appearance")]
/// <summary>
/// The color that the background is set to when a correct value is entered, before pressing enter.
/// </summary>
public Color CorrectColor { get; set; }
[Description("The color that the background is set to when an incorrect value is entered.")]
[Category("Appearance")]
/// <summary>
/// The color that the background is set to when an incorrect value is entered.
/// </summary>
public Color IncorrectColor { get; set; }
[Description("The default background color of the control.")]
[Category("Appearance")]
/// <summary>
/// The default background color of the control.
/// </summary>
public Color DefaultColor { get; set; }
[Description("Event raised when the internal value of the control was successfully changed.")]
[Category("Action")]
/// <summary>
/// Value of the control was successfully changed.
/// </summary>
public event EventHandler<EventArgs> ValueChanged;
[Description("Event raised when the Enter key was pressed on the control which reuslted in a successfull update of the value.")]
[Category("Action")]
/// <summary>
/// Enter was pressed on the control which resulted in a successful update of the value.
/// </summary>
public event EventHandler<EventArgs> EnterPressed;
public NumericWithUnit()
{
InitializeComponent();
// unitsAllowedUnits
AllowedUnits = new ObservableCollection<Unit>();
TestUnits = new List<Unit>();
// default units (blank one)
AllowedUnits.Add(new Unit());
Minimum = 0;
Maximum = 1;
DecimalPlaces = 13;
DisplayFormat = null;
// defaults
CorrectColor = Color.LightGreen;
IncorrectColor = Color.Red;
DefaultColor = Color.White;
// initial build of regex
rebuildRegex();
// listeners
AllowedUnits.CollectionChanged += collectionChanged;
}
private void collectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// need to update?
if (e.Action == NotifyCollectionChangedAction.Add)
{
// reorder
AllowedUnits = new ObservableCollection<Unit>(AllowedUnits.OrderByDescending(a => a.UnitValue));
AllowedUnits.CollectionChanged += collectionChanged;
// rebuild regexes
rebuildRegex();
}
}
private void rebuildRegex()
{
string regexString = numberRegexString;
// add the formatsz
unitsRegexString = "";
if (AllowedUnits.Count > 0)
{
unitsRegexString = "(";
for (int i = 0; i < AllowedUnits.Count; i++)
{
unitsRegexString += AllowedUnits[i].UnitString + "|";
}
unitsRegexString = unitsRegexString.Remove(unitsRegexString.Length - 1); // remove trailing "|"
unitsRegexString += ")(?<=[\\s]*)$";
}
else
{
unitsRegexString = "(?<=[\\s]*)$";
}
formatRegex = new Regex(regexString + unitsRegexString);
}
/// <summary>
/// Some taken from https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keycode(v=vs.110).aspx
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void OnKeyDown(KeyEventArgs e)
{
// reset
forbiddenKey = false;
enterKey = false;
// what was entered?
bool numberEntered = false;
bool letterEntered = false;
// from https://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.keycode(v=vs.110).aspx
// number key?
numberEntered = ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9)) && (Control.ModifierKeys != Keys.Shift);
// letter?
letterEntered = (e.KeyCode >= Keys.A && e.KeyCode <= Keys.Z);
// or other allowed keys?
bool allowed = numberEntered || letterEntered || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right || e.KeyCode == Keys.Home || e.KeyCode == Keys.End || e.KeyCode == Keys.Back || e.KeyCode == Keys.Delete || e.KeyCode == Keys.Space || e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod || e.KeyCode == Keys.OemMinus || e.KeyCode == Keys.Oemplus;
// enter?
enterKey = e.KeyCode == Keys.Enter;
// not allowed
if (!allowed && !enterKey)
{
e.Handled = true;
e.SuppressKeyPress = true;
}
forbiddenKey = !allowed;
// call base
base.OnKeyDown(e);
}
/// <summary>
/// Raises the Control.KeyUp event.
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
// reset
forbiddenKey = false;
enterKey = false;
// call base
base.OnKeyUp(e);
}
protected override void OnLeave(EventArgs e)
{
// reset
forbiddenKey = false;
enterKey = false;
// call base
base.OnLeave(e);
}
/// <summary>
/// Key pressed. Check that format is correct.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (forbiddenKey)
{
e.Handled = true;
}
// enter?
if (enterKey)
{
VerifyInput();
}
// base
base.OnKeyPress(e);
}
/// <summary>
/// Try to verify the input
/// </summary>
/// <returns></returns>
public bool VerifyInput()
{
// try to convert
double number;
bool verified = extractValue(out number);
if (verified)
{
// succes, set value and clear BG colour
value = number;
BackColor = DefaultColor;
if (ValueChanged != null) ValueChanged(this, new EventArgs());
// make text as user may have entered just a number
allowTextUpdateEvent = false;
Text = makeString(value);
allowTextUpdateEvent = true;
// was enter pressed to get here?
if (enterKey)
{
// reset and fire event
enterKey = false; // must reset in case the handler has VerifyInput() inside => stack overflow
if (EnterPressed != null) EnterPressed(this, new EventArgs());
}
}
else
{
BackColor = IncorrectColor;
}
return verified;
}
private bool allowTextUpdateEvent = true;
/// <summary>
/// Text internally changed.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected override void OnTextChanged(EventArgs e)
{
if (!allowTextUpdateEvent) return;
bool allowed = false;
double number;
allowed = extractValue(out number);
BackColor = !internalSet ? (allowed ? CorrectColor : IncorrectColor) : DefaultColor;
internalSet = false;
// base
base.OnTextChanged(e);
}
/// <summary>
/// Take the current value of the text box and try to extract it.
/// </summary>
/// <param name="?">True if the number written is within the range of the box and correctly formatted.</param>
/// <returns></returns>
private bool extractValue(out double number)
{
MatchCollection matches = formatRegex.Matches(Text.Trim());
number = -1;
bool allowed = false;
// matched?
if (matches.Count == 1)
{
// try to extract the number and the unit
string numberString = new Regex(numberRegexString).Match(Text.Trim()).Value.Trim();
string unit = new Regex(unitsRegexString).Match(Text.Trim()).Value.Trim();
// try to parse
if (Double.TryParse(numberString, out number))
{
double unitValue = 1;
if (AllowedUnits.Count > 0)
{
unitValue = AllowedUnits.Where(uw => uw.UnitString == unit).ToList()[0].UnitValue;
}
// get real value
number = number * unitValue;
// round to decimal places
number = Math.Round(number, DecimalPlaces);
// within limits?
if (number >= Minimum && number <= Maximum)
{
allowed = true;
}
}
}
return allowed;
}
/// <summary>
/// Take a value, and make a test string using the appropriate unit
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
private string makeString(double value)
{
Unit unit;
string numberText;
if (AllowedUnits.Count > 0)
{
// to find the best unit, got throug all units until we find one that is lower than the value
// if none is found, use the smallest
unit = AllowedUnits[AllowedUnits.Count - 1];
for (int i = 0; i < AllowedUnits.Count; i++)
{
// skip if the base unit (1)
if (AllowedUnits[i].UnitString == "") continue;
if (Math.Abs(AllowedUnits[i].UnitValue) <= Math.Abs(value))
{
// pic this unit
unit = AllowedUnits[i];
break;
}
}
// make text
if (DisplayFormat == null)
{
numberText = "" + value / unit.UnitValue + (unit.UnitString == "" ? "" : " " + unit.UnitString);
}
else
{
numberText = String.Format(DisplayFormat, value / unit.UnitValue, unit.UnitString);
}
}
else
{
// else assume no unit
numberText = "" + value;
}
return numberText;
}
}
}