Free cookie consent management tool by TermsFeed Policy Generator

source: branches/histogram/HeuristicLab.Analysis.Views/3.3/DataTableView.cs @ 6253

Last change on this file since 6253 was 6176, checked in by abeham, 14 years ago

#1465

  • Removed properties menu from EnhancedChart
  • Added IConfigureableView interface to DataTableView
File size: 28.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.Collections;
29using HeuristicLab.Core.Views;
30using HeuristicLab.MainForm;
31
32namespace HeuristicLab.Analysis.Views {
33  /// <summary>
34  /// The visual representation of a <see cref="Variable"/>.
35  /// </summary>
36  [View("DataTable View")]
37  [Content(typeof(DataTable), true)]
38  public partial class DataTableView : NamedItemView, IConfigureableView {
39    protected List<Series> invisibleSeries;
40    protected Dictionary<IObservableList<double>, DataRow> valuesRowsTable;
41    /// <summary>
42    /// Gets or sets the variable to represent visually.
43    /// </summary>
44    /// <remarks>Uses property <see cref="ViewBase.Item"/> of base class <see cref="ViewBase"/>.
45    /// No own data storage present.</remarks>
46    public new DataTable Content {
47      get { return (DataTable)base.Content; }
48      set { base.Content = value; }
49    }
50
51    /// <summary>
52    /// Initializes a new instance of <see cref="VariableView"/> with caption "Variable".
53    /// </summary>
54    public DataTableView() {
55      InitializeComponent();
56      valuesRowsTable = new Dictionary<IObservableList<double>, DataRow>();
57      invisibleSeries = new List<Series>();
58      chart.CustomizeAllChartAreas();
59      chart.ChartAreas[0].CursorX.Interval = 1;
60    }
61
62    #region Event Handler Registration
63    /// <summary>
64    /// Removes the eventhandlers from the underlying <see cref="Variable"/>.
65    /// </summary>
66    /// <remarks>Calls <see cref="ViewBase.RemoveItemEvents"/> of base class <see cref="ViewBase"/>.</remarks>
67    protected override void DeregisterContentEvents() {
68      foreach (DataRow row in Content.Rows)
69        DeregisterDataRowEvents(row);
70      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
71      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
72      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
73      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
74      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
75      base.DeregisterContentEvents();
76    }
77
78    /// <summary>
79    /// Adds eventhandlers to the underlying <see cref="Variable"/>.
80    /// </summary>
81    /// <remarks>Calls <see cref="ViewBase.AddItemEvents"/> of base class <see cref="ViewBase"/>.</remarks>
82    protected override void RegisterContentEvents() {
83      base.RegisterContentEvents();
84      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
85      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded);
86      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved);
87      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced);
88      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset);
89      foreach (DataRow row in Content.Rows)
90        RegisterDataRowEvents(row);
91    }
92
93    /// <summary>
94    /// Automatically called for every existing data row and whenever a data row is added
95    /// to the data table. Do not call this method directly.
96    /// </summary>
97    /// <param name="row">The DataRow that was added.</param>
98    protected virtual void RegisterDataRowEvents(DataRow row) {
99      row.NameChanged += new EventHandler(Row_NameChanged);
100      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
101      valuesRowsTable.Add(row.Values, row);
102      row.Values.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
103      row.Values.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
104      row.Values.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
105      row.Values.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
106      row.Values.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
107    }
108
109    /// <summary>
110    /// Automatically called for every data row that is removed from the DataTable. Do
111    /// not directly call this method.
112    /// </summary>
113    /// <param name="row">The DataRow that was removed.</param>
114    protected virtual void DeregisterDataRowEvents(DataRow row) {
115      row.Values.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded);
116      row.Values.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved);
117      row.Values.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced);
118      row.Values.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved);
119      row.Values.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset);
120      valuesRowsTable.Remove(row.Values);
121      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
122      row.NameChanged -= new EventHandler(Row_NameChanged);
123    }
124    #endregion
125
126    protected override void OnContentChanged() {
127      base.OnContentChanged();
128      invisibleSeries.Clear();
129      chart.Titles[0].Text = string.Empty;
130      chart.ChartAreas[0].AxisX.Title = string.Empty;
131      chart.ChartAreas[0].AxisY.Title = string.Empty;
132      chart.ChartAreas[0].AxisY2.Title = string.Empty;
133      chart.Series.Clear();
134      if (Content != null) {
135        chart.Titles[0].Text = Content.Name;
136        foreach (DataRow row in Content.Rows)
137          AddDataRow(row);
138        ConfigureChartArea(chart.ChartAreas[0]);
139        RecalculateAxesScale(chart.ChartAreas[0]);
140      }
141    }
142
143    protected override void SetEnabledStateOfControls() {
144      base.SetEnabledStateOfControls();
145      chart.Enabled = Content != null;
146    }
147
148    public void ShowConfiguration() {
149      if (Content != null) {
150        DataTableVisualPropertiesDialog dialog = new DataTableVisualPropertiesDialog(Content);
151        dialog.ShowDialog();
152      } else MessageBox.Show("Nothing to configure.");
153    }
154
155    /// <summary>
156    /// Add the DataRow as a series to the chart.
157    /// </summary>
158    /// <param name="row">DataRow to add as series to the chart.</param>
159    protected virtual void AddDataRow(DataRow row) {
160      Series series = new Series(row.Name);
161      ConfigureSeries(series, row);
162      FillSeriesWithRowValues(series, row);
163
164      chart.Series.Add(series);
165      ConfigureChartArea(chart.ChartAreas[0]);
166      RecalculateAxesScale(chart.ChartAreas[0]);
167      UpdateYCursorInterval();
168    }
169
170    private void ConfigureSeries(Series series, DataRow row) {
171      RemoveCustomPropertyIfExists(series, "PointWidth");
172      series.BorderWidth = 1;
173      series.BorderDashStyle = ChartDashStyle.Solid;
174      series.BorderColor = Color.Empty;
175
176      if (row.VisualProperties.Color != Color.Empty)
177        series.Color = row.VisualProperties.Color;
178      else series.Color = Color.Empty;
179
180      switch (row.VisualProperties.ChartType) {
181        case DataRowVisualProperties.DataRowChartType.Line:
182          series.ChartType = SeriesChartType.FastLine;
183          series.BorderWidth = row.VisualProperties.LineWidth;
184          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
185          break;
186        case DataRowVisualProperties.DataRowChartType.Bars:
187          // Bar is incompatible with anything but Bar and StackedBar*
188          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100))
189            series.ChartType = SeriesChartType.Bar;
190          else {
191            series.ChartType = SeriesChartType.FastPoint; //default
192            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
193          }
194          break;
195        case DataRowVisualProperties.DataRowChartType.Columns:
196          series.ChartType = SeriesChartType.Column;
197          break;
198        case DataRowVisualProperties.DataRowChartType.Points:
199          series.ChartType = SeriesChartType.FastPoint;
200          break;
201        case DataRowVisualProperties.DataRowChartType.Histogram:
202          series.ChartType = SeriesChartType.Column;
203          series.SetCustomProperty("PointWidth", "1");
204          if (!series.Color.IsEmpty && series.Color.GetBrightness() < 0.25)
205            series.BorderColor = Color.White;
206          else series.BorderColor = Color.Black;
207          break;
208        default:
209          series.ChartType = SeriesChartType.FastPoint;
210          break;
211      }
212      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
213      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
214      series.ToolTip = row.Name + " X = #INDEX, Y = #VAL";
215    }
216
217    private void ConfigureChartArea(ChartArea area) {
218      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
219      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
220
221      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
222      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
223      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
224
225      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
226      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
227      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
228
229      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
230      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
231      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
232
233      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
234      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
235      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
236    }
237
238    private void RecalculateAxesScale(ChartArea area) {
239      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
240      foreach (Axis a in area.Axes) {
241        a.Minimum = double.NaN;
242        a.Maximum = double.NaN;
243      }
244      area.RecalculateAxesScale();
245      area.AxisX.IsMarginVisible = false;
246      area.AxisX2.IsMarginVisible = false;
247
248      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
249      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
250      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
251      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
252      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
253      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
254      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
255      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
256      if (area.AxisX.Minimum > area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
257      if (area.AxisX2.Minimum > area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
258      if (area.AxisY.Minimum > area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
259      if (area.AxisY2.Minimum > area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
260    }
261
262    /// <summary>
263    /// Set the Y Cursor interval to visible points of enabled series.
264    /// </summary>
265    protected virtual void UpdateYCursorInterval() {
266      double interestingValuesRange = (
267        from series in chart.Series
268        where series.Enabled
269        let values = (from point in series.Points
270                      where !point.IsEmpty
271                      select point.YValues[0]).DefaultIfEmpty(1.0)
272        let range = values.Max() - values.Min()
273        where range > 0.0
274        select range
275        ).DefaultIfEmpty(1.0).Min();
276
277      double digits = (int)Math.Log10(interestingValuesRange) - 3;
278      double yZoomInterval = Math.Pow(10, digits);
279      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
280    }
281
282
283    /// <summary>
284    /// Remove the corresponding series for a certain DataRow.
285    /// </summary>
286    /// <param name="row">DataRow which series should be removed.</param>
287    protected virtual void RemoveDataRow(DataRow row) {
288      Series series = chart.Series[row.Name];
289      chart.Series.Remove(series);
290      if (invisibleSeries.Contains(series))
291        invisibleSeries.Remove(series);
292      RecalculateAxesScale(chart.ChartAreas[0]);
293    }
294
295    #region Event Handlers
296    #region Content Event Handlers
297    protected override void Content_NameChanged(object sender, EventArgs e) {
298      if (InvokeRequired)
299        Invoke(new EventHandler(Content_NameChanged), sender, e);
300      else {
301        chart.Titles[0].Text = Content.Name;
302        base.Content_NameChanged(sender, e);
303      }
304    }
305    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
306      if (InvokeRequired)
307        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
308      else {
309        ConfigureChartArea(chart.ChartAreas[0]);
310        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
311      }
312    }
313    #endregion
314    #region Rows Event Handlers
315    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
316      if (InvokeRequired)
317        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsAdded), sender, e);
318      else {
319        foreach (DataRow row in e.Items) {
320          AddDataRow(row);
321          RegisterDataRowEvents(row);
322        }
323      }
324    }
325    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
326      if (InvokeRequired)
327        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsRemoved), sender, e);
328      else {
329        foreach (DataRow row in e.Items) {
330          DeregisterDataRowEvents(row);
331          RemoveDataRow(row);
332        }
333      }
334    }
335    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
336      if (InvokeRequired)
337        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_ItemsReplaced), sender, e);
338      else {
339        foreach (DataRow row in e.OldItems) {
340          DeregisterDataRowEvents(row);
341          RemoveDataRow(row);
342        }
343        foreach (DataRow row in e.Items) {
344          AddDataRow(row);
345          RegisterDataRowEvents(row);
346        }
347      }
348    }
349    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<DataRow> e) {
350      if (InvokeRequired)
351        Invoke(new CollectionItemsChangedEventHandler<DataRow>(Rows_CollectionReset), sender, e);
352      else {
353        foreach (DataRow row in e.OldItems) {
354          DeregisterDataRowEvents(row);
355          RemoveDataRow(row);
356        }
357        foreach (DataRow row in e.Items) {
358          AddDataRow(row);
359          RegisterDataRowEvents(row);
360        }
361      }
362    }
363    #endregion
364    #region Row Event Handlers
365    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
366      if (InvokeRequired)
367        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
368      else {
369        DataRow row = (DataRow)sender;
370        Series series = chart.Series[row.Name];
371        series.Points.Clear();
372        ConfigureSeries(series, row);
373        FillSeriesWithRowValues(series, row);
374        RecalculateAxesScale(chart.ChartAreas[0]);
375      }
376    }
377    private void Row_NameChanged(object sender, EventArgs e) {
378      if (InvokeRequired)
379        Invoke(new EventHandler(Row_NameChanged), sender, e);
380      else {
381        DataRow row = (DataRow)sender;
382        chart.Series[row.Name].Name = row.Name;
383      }
384    }
385    #endregion
386    #region Values Event Handlers
387    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
388      if (InvokeRequired)
389        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsAdded), sender, e);
390      else {
391        DataRow row = null;
392        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
393        if (row != null) {
394          Series rowSeries = chart.Series[row.Name];
395          if (!invisibleSeries.Contains(rowSeries)) {
396            rowSeries.Points.Clear();
397            FillSeriesWithRowValues(rowSeries, row);
398            RecalculateAxesScale(chart.ChartAreas[0]);
399            UpdateYCursorInterval();
400          }
401        }
402      }
403    }
404    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
405      if (InvokeRequired)
406        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsRemoved), sender, e);
407      else {
408        DataRow row = null;
409        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
410        if (row != null) {
411          Series rowSeries = chart.Series[row.Name];
412          if (!invisibleSeries.Contains(rowSeries)) {
413            rowSeries.Points.Clear();
414            FillSeriesWithRowValues(rowSeries, row);
415            RecalculateAxesScale(chart.ChartAreas[0]);
416            UpdateYCursorInterval();
417          }
418        }
419      }
420    }
421    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
422      if (InvokeRequired)
423        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsReplaced), sender, e);
424      else {
425        DataRow row = null;
426        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
427        if (row != null) {
428          Series rowSeries = chart.Series[row.Name];
429          if (!invisibleSeries.Contains(rowSeries)) {
430            if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
431              rowSeries.Points.Clear();
432              FillSeriesWithRowValues(rowSeries, row);
433            } else {
434              foreach (IndexedItem<double> item in e.Items) {
435                if (IsInvalidValue(item.Value))
436                  rowSeries.Points[item.Index].IsEmpty = true;
437                else {
438                  rowSeries.Points[item.Index].YValues = new double[] { item.Value };
439                  rowSeries.Points[item.Index].IsEmpty = false;
440                }
441              }
442            }
443            RecalculateAxesScale(chart.ChartAreas[0]);
444            UpdateYCursorInterval();
445          }
446        }
447      }
448    }
449    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
450      if (InvokeRequired)
451        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_ItemsMoved), sender, e);
452      else {
453        DataRow row = null;
454        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
455        if (row != null) {
456          Series rowSeries = chart.Series[row.Name];
457          if (!invisibleSeries.Contains(rowSeries)) {
458            rowSeries.Points.Clear();
459            FillSeriesWithRowValues(rowSeries, row);
460            RecalculateAxesScale(chart.ChartAreas[0]);
461            UpdateYCursorInterval();
462          }
463        }
464      }
465    }
466
467    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<double>> e) {
468      if (InvokeRequired)
469        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<double>>(Values_CollectionReset), sender, e);
470      else {
471        DataRow row = null;
472        valuesRowsTable.TryGetValue((IObservableList<double>)sender, out row);
473        if (row != null) {
474          Series rowSeries = chart.Series[row.Name];
475          if (!invisibleSeries.Contains(rowSeries)) {
476            rowSeries.Points.Clear();
477            FillSeriesWithRowValues(rowSeries, row);
478            RecalculateAxesScale(chart.ChartAreas[0]);
479            UpdateYCursorInterval();
480          }
481        }
482      }
483    }
484    #endregion
485    #endregion
486
487    #region Chart Event Handlers
488    private void chart_MouseDown(object sender, MouseEventArgs e) {
489      HitTestResult result = chart.HitTest(e.X, e.Y);
490      if (result.ChartElementType == ChartElementType.LegendItem) {
491        ToggleSeriesVisible(result.Series);
492      }
493    }
494    private void chart_MouseMove(object sender, MouseEventArgs e) {
495      HitTestResult result = chart.HitTest(e.X, e.Y);
496      if (result.ChartElementType == ChartElementType.LegendItem)
497        this.Cursor = Cursors.Hand;
498      else
499        this.Cursor = Cursors.Default;
500    }
501    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
502      foreach (LegendItem legendItem in e.LegendItems) {
503        var series = chart.Series[legendItem.SeriesName];
504        if (series != null) {
505          bool seriesIsInvisible = invisibleSeries.Contains(series);
506          foreach (LegendCell cell in legendItem.Cells) {
507            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
508          }
509        }
510      }
511    }
512    #endregion
513
514    private void ToggleSeriesVisible(Series series) {
515      if (!invisibleSeries.Contains(series)) {
516        series.Points.Clear();
517        invisibleSeries.Add(series);
518      } else {
519        invisibleSeries.Remove(series);
520        if (Content != null) {
521
522          var row = (from r in Content.Rows
523                     where r.Name == series.Name
524                     select r).Single();
525          FillSeriesWithRowValues(series, row);
526          this.chart.Legends[series.Legend].ForeColor = Color.Black;
527          RecalculateAxesScale(chart.ChartAreas[0]);
528          UpdateYCursorInterval();
529        }
530      }
531    }
532
533    private void FillSeriesWithRowValues(Series series, DataRow row) {
534      switch (row.VisualProperties.ChartType) {
535        case DataRowVisualProperties.DataRowChartType.Histogram:
536          CalculateHistogram(series, row);
537          break;
538        default: {
539            for (int i = 0; i < row.Values.Count; i++) {
540              var value = row.Values[i];
541              DataPoint point = new DataPoint();
542              point.XValue = row.VisualProperties.StartIndexZero ? i : i + 1;
543              if (IsInvalidValue(value))
544                point.IsEmpty = true;
545              else
546                point.YValues = new double[] { value };
547              series.Points.Add(point);
548            }
549          }
550          break;
551      }
552    }
553
554    protected virtual void CalculateHistogram(Series series, DataRow row) {
555      series.Points.Clear();
556      if (!row.Values.Any()) return;
557      int bins = row.VisualProperties.Bins;
558
559      double minValue = row.Values.Min();
560      double maxValue = row.Values.Max();
561      double intervalWidth = (maxValue - minValue) / bins;
562      if (intervalWidth < 0) return;
563      if (intervalWidth == 0) {
564        series.Points.AddXY(minValue, row.Values.Count);
565        return;
566      }
567
568      if (!row.VisualProperties.ExactBins) {
569        intervalWidth = HumanRoundRange(intervalWidth);
570        minValue = Math.Floor(minValue / intervalWidth) * intervalWidth;
571        maxValue = Math.Ceiling(maxValue / intervalWidth) * intervalWidth;
572      }
573
574      double current = minValue, intervalCenter = intervalWidth / 2.0;
575      int frequency = 0;
576      series.Points.AddXY(current - intervalCenter, 0); // so that the first column is not visually truncated
577      foreach (double v in row.Values.Where(x => !IsInvalidValue(x)).OrderBy(x => x)) {
578        while (v > current + intervalWidth) {
579          series.Points.AddXY(current + intervalCenter, frequency);
580          current += intervalWidth;
581          frequency = 0;
582        }
583        frequency++;
584      }
585      series.Points.AddXY(current + intervalCenter, frequency);
586      series.Points.AddXY(current + 3 * intervalCenter, 0); // so that the last column is not visually truncated
587    }
588
589    #region Helpers
590    protected void RemoveCustomPropertyIfExists(Series series, string property) {
591      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
592    }
593
594    private double HumanRoundRange(double range) {
595      double base10 = Math.Pow(10.0, Math.Floor(Math.Log10(range)));
596      double rounding = range / base10;
597      if (rounding <= 1.5) rounding = 1;
598      else if (rounding <= 2.25) rounding = 2;
599      else if (rounding <= 3.75) rounding = 2.5;
600      else if (rounding <= 7.5) rounding = 5;
601      else rounding = 10;
602      return rounding * base10;
603    }
604
605    private double HumanRoundMax(double max) {
606      double base10;
607      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
608      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
609      double rounding = (max > 0) ? base10 : -base10;
610      while (rounding < max) rounding += base10;
611      return rounding;
612    }
613
614    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
615      switch (dataRowLineStyle) {
616        case DataRowVisualProperties.DataRowLineStyle.Dash:
617          return ChartDashStyle.Dash;
618        case DataRowVisualProperties.DataRowLineStyle.DashDot:
619          return ChartDashStyle.DashDot;
620        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
621          return ChartDashStyle.DashDotDot;
622        case DataRowVisualProperties.DataRowLineStyle.Dot:
623          return ChartDashStyle.Dot;
624        case DataRowVisualProperties.DataRowLineStyle.NotSet:
625          return ChartDashStyle.NotSet;
626        case DataRowVisualProperties.DataRowLineStyle.Solid:
627          return ChartDashStyle.Solid;
628        default:
629          return ChartDashStyle.NotSet;
630      }
631    }
632
633    /// <summary>
634    /// Determines whether a double value can be displayed (converted to Decimal and not an NaN).
635    /// </summary>
636    /// <param name="x">The number to check.</param>
637    /// <returns><code>true</code> if the value can be safely shwon in the chart,
638    /// <code>false</code> otherwise.</returns>
639    protected static bool IsInvalidValue(double x) {
640      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
641    }
642    #endregion
643  }
644}
Note: See TracBrowser for help on using the repository browser.