aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Visuals/Knob/Knob.xaml.cs
blob: 357582a17f676d8b41e32620e13ac23a0aa8442d (plain)
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
559
560
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Tango.Visuals;

namespace Tango.Visuals
{
    /// <summary>
    /// <para><img class="classImage" src="../Media/VolumeKnob.png" /></para>
    /// Represents a knob control.
    /// </summary>
    public partial class Knob : UserControl
    {
        private List<Line> lines;
        private Line markLine;
        private Brush oldTicksHighlightBrush;
        private double initialAngle;
        private bool _showSmallMarkers;

        #region Events

        /// <summary>
        /// Occurs when the knob's value has changed.
        /// </summary>
        public event EventHandler<DoubleValueChangedEventArgs> ValueChanged;

        #endregion

        #region Private Methods

        private void SetValueFromMouse(double angle)
        {
            if (angle < -140)
            {
                angle = -140;
            }
            if (angle > 140)
            {
                angle = 140;
            }

            double value = angle + 140;
            value = ((value) * 100) / 280;
            value = (value * (Maximum - Minimum)) / 100;
            value += Minimum;

            if (value < Minimum)
            {
                Value = Minimum;
            }
            else if (value > Maximum)
            {
                Value = Maximum;
            }
            else
            {
                Value = value;
            }
        }

        private void SetAngle(double angle)
        {
            if (ellipseGrid != null)
            {
                ellipseGrid.RenderTransformOrigin = new Point(0.5, 0.5);
                ellipseGrid.RenderTransform = new RotateTransform(angle);
                ellipseGrid.InvalidateMeasure();
            }
        }

        private void LightMarkers()
        {
            if (ellipseGrid != null)
            {
                RotateTransform rotate = ellipseGrid.RenderTransform as RotateTransform;
                double currentAngle = rotate.Angle;

                if (lines != null)
                {
                    foreach (Line m in lines)
                    {
                        RotateTransform t = m.RenderTransform as RotateTransform;
                        if (currentAngle >= t.Angle)
                        {
                            m.Stroke = TicksHighlightBrush;
                        }
                        else
                        {
                            m.Stroke = TicksBrush;
                        }
                    }
                }
            }
        }

        private void RenderMarkers()
        {
            lines = new List<Line>();

            double angleChange = 280 / 20;
            double markChange = 5;
            double counter = 0;
            int marksCounter = 0;

            mainGrid.Children.OfType<Line>().ToList().ForEach(x => mainGrid.Children.Remove(x));
            ellipseGrid.Children.OfType<Line>().ToList().ForEach(x => mainGrid.Children.Remove(x));

            if (_showSmallMarkers)
            {
                for (int i = 0; i < 21; i++)
                {
                    Line line = new Line();
                    line.StrokeThickness = TicksWidth;
                    line.Stroke = TicksBrush;
                    line.X1 = this.ActualWidth / 2;
                    if ((marksCounter == markChange || marksCounter == 0))
                    {
                        line.Y1 = 0;
                        marksCounter = 0;
                    }
                    else
                    {
                        line.Y1 = 3;
                    }
                    line.X2 = this.ActualWidth / 2;
                    line.Y2 = TicksHeight;
                    mainGrid.Children.Add(line);
                    line.RenderTransform = new RotateTransform(counter - 140, this.ActualWidth / 2, this.ActualHeight / 2);
                    counter += angleChange;
                    marksCounter++;
                    lines.Add(line);
                }
            }

            ellipseGrid.Children.Remove(markLine);
            markLine = new Line();
            markLine.StrokeThickness = 2;
            markLine.Stroke = TicksHighlightBrush;
            markLine.X1 = ellipseGrid.ActualWidth / 2;
            markLine.Y1 = 5;
            markLine.X2 = markLine.X1;
            markLine.Y2 = (ellipseGrid.ActualWidth / 2) * 0.8;
            ellipseGrid.Children.Add(markLine);
        }

        private static BitmapSource GetImageFromApplicationResource(String resourcePath)
        {
            String callingAssembly = Assembly.GetCallingAssembly().GetName().Name;
            Uri uri = new Uri("/" + callingAssembly + ";component/" + resourcePath, UriKind.Relative);
            System.Windows.Resources.StreamResourceInfo info = Application.GetResourceStream(uri);

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapImage.StreamSource = info.Stream;
            bitmapImage.EndInit();
            return bitmapImage;
        }

        #endregion

        #region Virtual Methods

        /// <summary>
        /// Called when the value changed.
        /// </summary>
        protected virtual void OnValueChanged()
        {
            try
            {
                if (Value < Minimum)
                {
                    Value = Minimum;
                }

                if (Value > Maximum)
                {
                    Value = Maximum;
                }

                double angle = ((Value - Minimum) * 100) / (Maximum - Minimum);
                angle = ((angle * 280) / 100) - 140;

                SetAngle(angle);
                LightMarkers();
            }
            catch { }

            if (ValueChanged != null) ValueChanged(this, new DoubleValueChangedEventArgs(Value));
        }

        /// <summary>
        /// Invoked before the value has changed.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        protected virtual object OnCoerceValue(double value)
        {
            var v = SnapToValues ? Math.Round(value, SnapPercision) : value;
            return v;
        }

        /// <summary>
        /// Draws the knob.
        /// </summary>
        protected virtual void OnDrawKnob()
        {
            try
            {
                RenderMarkers();
                LightMarkers();

                if (KnobType == KnobType.MetroDark)
                {
                    img.Source = GetImageFromApplicationResource("Knob/volumeKnobMetroDark.png");
                }
                else if (KnobType == KnobType.MetroLight)
                {
                    img.Source = GetImageFromApplicationResource("Knob/volumeKnobMetroLight.png");
                }
                else if (KnobType == KnobType.Dark)
                {
                    img.Source = GetImageFromApplicationResource("Knob/volumeKnobDark.png");
                }
                else if (KnobType == KnobType.Light)
                {
                    img.Source = GetImageFromApplicationResource("Knob/volumeKnobLight.png");
                }
                else if (KnobType == KnobType.Complex)
                {
                    img.Source = GetImageFromApplicationResource("Knob/volumeKnobComplex.png");
                }


            }
            catch { }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the ticks highlight brush.
        /// </summary>
        public Brush TicksHighlightBrush
        {
            get { return (Brush)GetValue(TicksHighlightBrushProperty); }
            set { SetValue(TicksHighlightBrushProperty, value); }
        }
        public static readonly DependencyProperty TicksHighlightBrushProperty =
            DependencyProperty.Register("TicksHighlightBrush", typeof(Brush), typeof(Knob), new PropertyMetadata(Brushes.Red, OnPropertiesChanged));

        /// <summary>
        /// Gets or sets the ticks brush.
        /// </summary>
        public Brush TicksBrush
        {
            get { return (Brush)GetValue(TicksBrushProperty); }
            set { SetValue(TicksBrushProperty, value); }
        }
        public static readonly DependencyProperty TicksBrushProperty =
            DependencyProperty.Register("TicksBrush", typeof(Brush), typeof(Knob), new PropertyMetadata(Brushes.DimGray, OnPropertiesChanged));

        /// <summary>
        /// Gets or sets the type of the knob.
        /// </summary>
        public KnobType KnobType
        {
            get { return (KnobType)GetValue(KnobTypeProperty); }
            set { SetValue(KnobTypeProperty, value); }
        }
        public static readonly DependencyProperty KnobTypeProperty =
            DependencyProperty.Register("KnobType", typeof(KnobType), typeof(Knob), new PropertyMetadata(KnobType.Dark, OnPropertiesChanged));

        /// <summary>
        /// Gets or sets amount of change when using keyboard arrows.
        /// </summary>
        public double Change
        {
            get { return (double)GetValue(ChangeProperty); }
            set { SetValue(ChangeProperty, value); }
        }
        public static readonly DependencyProperty ChangeProperty =
            DependencyProperty.Register("Change", typeof(double), typeof(Knob), new PropertyMetadata(1.0));

        /// <summary>
        /// Gets or sets the width of the ticks.
        /// </summary>
        public double TicksWidth
        {
            get { return (double)GetValue(TicksWidthProperty); }
            set { SetValue(TicksWidthProperty, value); }
        }
        public static readonly DependencyProperty TicksWidthProperty =
            DependencyProperty.Register("TicksWidth", typeof(double), typeof(Knob), new PropertyMetadata(3.0, OnPropertiesChanged));

        /// <summary>
        /// Gets or sets the height of the ticks.
        /// </summary>
        public double TicksHeight
        {
            get { return (double)GetValue(TicksHeightProperty); }
            set { SetValue(TicksHeightProperty, value); }
        }
        public static readonly DependencyProperty TicksHeightProperty =
            DependencyProperty.Register("TicksHeight", typeof(double), typeof(Knob), new PropertyMetadata(10.0, OnPropertiesChanged));

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        public double Value
        {
            get { return (double)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, SnapToValues ? Math.Round(value, SnapPercision) : value); }
        }
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(double), typeof(Knob), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => (d as Knob).OnValueChanged(), (d, value) => (d as Knob).OnCoerceValue((double)value)));

        /// <summary>
        /// Gets or sets the minimum value.
        /// </summary>
        public double Minimum
        {
            get { return (double)GetValue(MinimumProperty); }
            set { SetValue(MinimumProperty, value); }
        }
        public static readonly DependencyProperty MinimumProperty =
            DependencyProperty.Register("Minimum", typeof(double), typeof(Knob), new PropertyMetadata(0.0, OnPropertiesChanged));

        public bool SnapToValues
        {
            get { return (bool)GetValue(SnapToValuesProperty); }
            set { SetValue(SnapToValuesProperty, value); }
        }
        public static readonly DependencyProperty SnapToValuesProperty =
            DependencyProperty.Register("SnapToValues", typeof(bool), typeof(Knob), new PropertyMetadata(false));

        public int SnapPercision
        {
            get { return (int)GetValue(SnapPercisionProperty); }
            set { SetValue(SnapPercisionProperty, value); }
        }
        public static readonly DependencyProperty SnapPercisionProperty =
            DependencyProperty.Register("SnapPercision", typeof(int), typeof(Knob), new PropertyMetadata(1));

        /// <summary>
        /// Gets or sets the maximum value.
        /// </summary>
        public double Maximum
        {
            get { return (double)GetValue(MaximumProperty); }
            set { SetValue(MaximumProperty, value); }
        }
        public static readonly DependencyProperty MaximumProperty =
            DependencyProperty.Register("Maximum", typeof(double), typeof(Knob), new PropertyMetadata(1.0, OnPropertiesChanged));
        private static void OnPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as Knob).OnDrawKnob();
            (d as Knob).OnValueChanged();
        }

        #endregion

        #region Constructors

        public Knob()
        {
            _showSmallMarkers = true;
            InitializeComponent();
            this.Loaded += Knob_Loaded;
            moveThumb.AddHandler(Thumb.MouseEnterEvent, new MouseEventHandler(ellipseGrid_MouseEnter), true);
            moveThumb.AddHandler(Thumb.MouseLeaveEvent, new MouseEventHandler(ellipseGrid_MouseLeave), true);
            this.AddHandler(UserControl.PreviewKeyDownEvent, new KeyEventHandler(Knob_PreviewKeyDown), true);
            this.PreviewMouseDown += Knob_PreviewMouseDown;
            this.Focusable = true;

            KnobType = KnobType.MetroLight;

            this.IsEnabledChanged += Knob_IsEnabledChanged;

            moveThumb.DragStarted += moveThumb_DragStarted;
            moveThumb.DragDelta += moveThumb_DragDelta;

            this.SizeChanged += VolumeKnob_SizeChanged;
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the SizeChanged event of the VolumeKnob control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="SizeChangedEventArgs"/> instance containing the event data.</param>
        private void VolumeKnob_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            OnDrawKnob();
        }

        /// <summary>
        /// Handles the DragDelta event of the moveThumb control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DragDeltaEventArgs"/> instance containing the event data.</param>
        private void moveThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            double angle = 0;

            angle = e.VerticalChange * -1;

            angle = this.initialAngle + angle;

            this.SetValueFromMouse(angle);
        }

        /// <summary>
        /// Handles the DragStarted event of the moveThumb control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DragStartedEventArgs"/> instance containing the event data.</param>
        private void moveThumb_DragStarted(object sender, DragStartedEventArgs e)
        {
            Point startPoint = Mouse.GetPosition(ellipseGrid);

            RotateTransform t = ellipseGrid.RenderTransform as RotateTransform;
            if (t != null)
            {
                this.initialAngle = t.Angle;
            }
        }

        /// <summary>
        /// Handles the IsEnabledChanged event of the Knob control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private void Knob_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue == e.OldValue) return;

            if (IsEnabled)
            {
                TicksHighlightBrush = oldTicksHighlightBrush;
                RenderMarkers();
            }
            else
            {
                oldTicksHighlightBrush = TicksHighlightBrush;
                TicksHighlightBrush = Brushes.Gray;
                RenderMarkers();
            }
        }

        /// <summary>
        /// Handles the PreviewMouseDown event of the Knob control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
        private void Knob_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            this.FocusVisualStyle = null;
            this.Focusable = true;
            this.Focus();
        }

        /// <summary>
        /// Handles the PreviewKeyDown event of the Knob control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyEventArgs"/> instance containing the event data.</param>
        private void Knob_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Up && Value < Maximum)
            {
                Value += Change;
            }
            else if (e.Key == Key.Down && Value > Minimum)
            {
                Value -= Change;
            }

            this.Focusable = true;
            this.Focus();
            e.Handled = true;
        }

        /// <summary>
        /// Handles the Loaded event of the Knob control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void Knob_Loaded(object sender, RoutedEventArgs e)
        {
            OnDrawKnob();
        }

        /// <summary>
        /// Handles the MouseLeave event of the ellipseGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void ellipseGrid_MouseLeave(object sender, MouseEventArgs e)
        {
            DoubleAnimation maskAni = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(200)));

            maskEllipse.Fill.BeginAnimation(RadialGradientBrush.OpacityProperty, maskAni);

            DoubleAnimation glowAni = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(200)));
            glowEllipse.BeginAnimation(OpacityProperty, glowAni);

            //DoubleAnimation efxAni = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(200)));
            //glowEffect.BeginAnimation(OpacityProperty, efxAni);

            DoubleAnimation glow = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(200)));
            imgGlow.BeginAnimation(RadialGradientBrush.OpacityProperty, glow);
        }

        /// <summary>
        /// Handles the MouseEnter event of the ellipseGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="MouseEventArgs"/> instance containing the event data.</param>
        private void ellipseGrid_MouseEnter(object sender, MouseEventArgs e)
        {
            DoubleAnimation maskAni = new DoubleAnimation(0.5, new Duration(TimeSpan.FromMilliseconds(200)));

            maskEllipse.Fill.BeginAnimation(RadialGradientBrush.OpacityProperty, maskAni);

            DoubleAnimation glowAni = new DoubleAnimation(1, new Duration(TimeSpan.FromMilliseconds(200)));
            glowEllipse.BeginAnimation(OpacityProperty, glowAni);

            //DoubleAnimation efxAni = new DoubleAnimation(1, new Duration(TimeSpan.FromMilliseconds(200)));
            //glowEffect.BeginAnimation(OpacityProperty, efxAni);

            DoubleAnimation glow = new DoubleAnimation(0.5, new Duration(TimeSpan.FromMilliseconds(200)));
            imgGlow.BeginAnimation(RadialGradientBrush.OpacityProperty, glow);

        }

        #endregion
    }
}