Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Analysis.Views/3.3/IndexedDataTableView.cs @ 13391

Last change on this file since 13391 was 12865, checked in by abeham, 9 years ago

#2431:

  • Added label on last data point
  • Changed target in cost view to display as ratio to best-known or best found
File size: 28.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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  [View("IndexedDataTable View")]
34  [Content(typeof(IndexedDataTable<>), true)]
35  public partial class IndexedDataTableView<T> : NamedItemView {
36    protected List<Series> invisibleSeries;
37    protected Dictionary<IObservableList<Tuple<T, double>>, IndexedDataRow<T>> valuesRowsTable;
38
39    public new IndexedDataTable<T> Content {
40      get { return (IndexedDataTable<T>)base.Content; }
41      set { base.Content = value; }
42    }
43
44    public IndexedDataTableView() {
45      InitializeComponent();
46      valuesRowsTable = new Dictionary<IObservableList<Tuple<T, double>>, IndexedDataRow<T>>();
47      invisibleSeries = new List<Series>();
48      chart.CustomizeAllChartAreas();
49      chart.ChartAreas[0].CursorX.Interval = 1;
50      chart.SuppressExceptions = true;
51    }
52
53    #region Event Handler Registration
54    protected override void DeregisterContentEvents() {
55      foreach (var row in Content.Rows)
56        DeregisterDataRowEvents(row);
57      Content.VisualPropertiesChanged -= new EventHandler(Content_VisualPropertiesChanged);
58      Content.Rows.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded);
59      Content.Rows.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved);
60      Content.Rows.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced);
61      Content.Rows.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset);
62      base.DeregisterContentEvents();
63    }
64
65    protected override void RegisterContentEvents() {
66      base.RegisterContentEvents();
67      Content.VisualPropertiesChanged += new EventHandler(Content_VisualPropertiesChanged);
68      Content.Rows.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded);
69      Content.Rows.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved);
70      Content.Rows.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced);
71      Content.Rows.CollectionReset += new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset);
72      foreach (var row in Content.Rows)
73        RegisterDataRowEvents(row);
74    }
75
76    /// <summary>
77    /// Automatically called for every existing data row and whenever a data row is added
78    /// to the data table. Do not call this method directly.
79    /// </summary>
80    /// <param name="row">The DataRow that was added.</param>
81    protected virtual void RegisterDataRowEvents(IndexedDataRow<T> row) {
82      row.NameChanged += new EventHandler(Row_NameChanged);
83      row.VisualPropertiesChanged += new EventHandler(Row_VisualPropertiesChanged);
84      valuesRowsTable.Add(row.Values, row);
85      row.Values.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded);
86      row.Values.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved);
87      row.Values.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced);
88      row.Values.ItemsMoved += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved);
89      row.Values.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset);
90    }
91
92    /// <summary>
93    /// Automatically called for every data row that is removed from the DataTable. Do
94    /// not directly call this method.
95    /// </summary>
96    /// <param name="row">The DataRow that was removed.</param>
97    protected virtual void DeregisterDataRowEvents(IndexedDataRow<T> row) {
98      row.Values.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded);
99      row.Values.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved);
100      row.Values.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced);
101      row.Values.ItemsMoved -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved);
102      row.Values.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset);
103      valuesRowsTable.Remove(row.Values);
104      row.VisualPropertiesChanged -= new EventHandler(Row_VisualPropertiesChanged);
105      row.NameChanged -= new EventHandler(Row_NameChanged);
106    }
107    #endregion
108
109    protected override void OnContentChanged() {
110      base.OnContentChanged();
111      invisibleSeries.Clear();
112      chart.Titles[0].Text = string.Empty;
113      chart.ChartAreas[0].AxisX.Title = string.Empty;
114      chart.ChartAreas[0].AxisY.Title = string.Empty;
115      chart.ChartAreas[0].AxisY2.Title = string.Empty;
116      chart.ChartAreas[0].AxisX.IsLogarithmic = false;
117      chart.ChartAreas[0].AxisX2.IsLogarithmic = false;
118      chart.ChartAreas[0].AxisY.IsLogarithmic = false;
119      chart.ChartAreas[0].AxisY2.IsLogarithmic = false;
120      chart.Series.Clear();
121      if (Content != null) {
122        chart.Titles[0].Text = Content.Name;
123        foreach (var row in Content.Rows)
124          AddDataRow(row);
125        ConfigureChartArea(chart.ChartAreas[0]);
126        RecalculateAxesScale(chart.ChartAreas[0]);
127      }
128    }
129
130    protected override void SetEnabledStateOfControls() {
131      base.SetEnabledStateOfControls();
132      chart.Enabled = Content != null;
133    }
134
135    /// <summary>
136    /// Add the DataRow as a series to the chart.
137    /// </summary>
138    /// <param name="row">DataRow to add as series to the chart.</param>
139    protected virtual void AddDataRow(IndexedDataRow<T> row) {
140      if (row.Values.Count == 0) return;
141
142      Series series = new Series(row.Name);
143      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
144      else series.LegendText = row.Name;
145      ConfigureSeries(series, row);
146      FillSeriesWithRowValues(series, row);
147
148      chart.Series.Add(series);
149      ConfigureChartArea(chart.ChartAreas[0]);
150      RecalculateAxesScale(chart.ChartAreas[0]);
151      UpdateYCursorInterval();
152    }
153
154    private void ConfigureSeries(Series series, IndexedDataRow<T> row) {
155      RemoveCustomPropertyIfExists(series, "PointWidth");
156      series.BorderWidth = 1;
157      series.BorderDashStyle = ChartDashStyle.Solid;
158      series.BorderColor = Color.Empty;
159
160      if (row.VisualProperties.Color != Color.Empty)
161        series.Color = row.VisualProperties.Color;
162      else series.Color = Color.Empty;
163      series.IsVisibleInLegend = row.VisualProperties.IsVisibleInLegend;
164
165      series.SmartLabelStyle.Enabled = true;
166      series.SmartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.Yes;
167      series.SmartLabelStyle.CalloutLineAnchorCapStyle = LineAnchorCapStyle.None;
168      series.SmartLabelStyle.CalloutLineColor = series.Color;
169      series.SmartLabelStyle.CalloutLineWidth = 2;
170      series.SmartLabelStyle.CalloutStyle = LabelCalloutStyle.Underlined;
171      series.SmartLabelStyle.IsOverlappedHidden = false;
172      series.SmartLabelStyle.MaxMovingDistance = 200;
173
174      switch (row.VisualProperties.ChartType) {
175        case DataRowVisualProperties.DataRowChartType.Line:
176          series.ChartType = SeriesChartType.FastLine;
177          series.BorderWidth = row.VisualProperties.LineWidth;
178          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
179          break;
180        case DataRowVisualProperties.DataRowChartType.Bars:
181          // Bar is incompatible with anything but Bar and StackedBar*
182          if (!chart.Series.Any(x => x.ChartType != SeriesChartType.Bar && x.ChartType != SeriesChartType.StackedBar && x.ChartType != SeriesChartType.StackedBar100)) {
183            series.ChartType = SeriesChartType.Bar;
184            chart.ChartAreas[0].AxisX.Interval = 1;
185          } else {
186            series.ChartType = SeriesChartType.FastPoint; //default
187            row.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Points;
188          }
189          break;
190        case DataRowVisualProperties.DataRowChartType.Columns:
191          series.ChartType = SeriesChartType.Column;
192          break;
193        case DataRowVisualProperties.DataRowChartType.Points:
194          series.ChartType = SeriesChartType.FastPoint;
195          break;
196        case DataRowVisualProperties.DataRowChartType.StepLine:
197          series.ChartType = SeriesChartType.StepLine;
198          series.BorderWidth = row.VisualProperties.LineWidth;
199          series.BorderDashStyle = ConvertLineStyle(row.VisualProperties.LineStyle);
200          break;
201        default:
202          series.ChartType = SeriesChartType.FastPoint;
203          break;
204      }
205      series.YAxisType = row.VisualProperties.SecondYAxis ? AxisType.Secondary : AxisType.Primary;
206      series.XAxisType = row.VisualProperties.SecondXAxis ? AxisType.Secondary : AxisType.Primary;
207      if (row.VisualProperties.DisplayName.Trim() != String.Empty) series.LegendText = row.VisualProperties.DisplayName;
208      else series.LegendText = row.Name;
209      series.ToolTip = series.LegendText + " X = #VALX, Y = #VALY";
210    }
211
212    private void ConfigureChartArea(ChartArea area) {
213      if (Content.VisualProperties.TitleFont != null) chart.Titles[0].Font = Content.VisualProperties.TitleFont;
214      if (!Content.VisualProperties.TitleColor.IsEmpty) chart.Titles[0].ForeColor = Content.VisualProperties.TitleColor;
215
216      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX.TitleFont = Content.VisualProperties.AxisTitleFont;
217      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX.TitleForeColor = Content.VisualProperties.AxisTitleColor;
218      area.AxisX.Title = Content.VisualProperties.XAxisTitle;
219
220      if (Content.VisualProperties.AxisTitleFont != null) area.AxisX2.TitleFont = Content.VisualProperties.AxisTitleFont;
221      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisX2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
222      area.AxisX2.Title = Content.VisualProperties.SecondXAxisTitle;
223
224      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY.TitleFont = Content.VisualProperties.AxisTitleFont;
225      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY.TitleForeColor = Content.VisualProperties.AxisTitleColor;
226      area.AxisY.Title = Content.VisualProperties.YAxisTitle;
227
228      if (Content.VisualProperties.AxisTitleFont != null) area.AxisY2.TitleFont = Content.VisualProperties.AxisTitleFont;
229      if (!Content.VisualProperties.AxisTitleColor.IsEmpty) area.AxisY2.TitleForeColor = Content.VisualProperties.AxisTitleColor;
230      area.AxisY2.Title = Content.VisualProperties.SecondYAxisTitle;
231
232      if (typeof(T).Equals(typeof(DateTime))) {
233        area.AxisX.IntervalType = DateTimeIntervalType.Hours;
234        area.AxisX.LabelStyle.Format = "dd.MM.yyyy HH:mm";
235        area.AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;
236      }
237    }
238
239    private void RecalculateAxesScale(ChartArea area) {
240      // Reset the axes bounds so that RecalculateAxesScale() will assign new bounds
241      foreach (Axis a in area.Axes) {
242        a.Minimum = double.NaN;
243        a.Maximum = double.NaN;
244      }
245
246      if (chart.Series.Any(x => x.Enabled && x.XAxisType == AxisType.Primary && (x.Points.Count == 0 || x.Points.Any(y => y.XValue <= 0))))
247        area.AxisX.IsLogarithmic = false;
248      else area.AxisX.IsLogarithmic = Content.VisualProperties.XAxisLogScale;
249      if (chart.Series.Any(x => x.Enabled && x.XAxisType == AxisType.Secondary && (x.Points.Count == 0 || x.Points.Any(y => y.XValue <= 0))))
250        area.AxisX2.IsLogarithmic = false;
251      else area.AxisX2.IsLogarithmic = Content.VisualProperties.SecondXAxisLogScale;
252
253      if (chart.Series.Any(x => x.Enabled && x.YAxisType == AxisType.Primary && (x.Points.Count == 0 || x.Points.Any(y => y.YValues.Min() <= 0))))
254        area.AxisY.IsLogarithmic = false;
255      else area.AxisY.IsLogarithmic = Content.VisualProperties.YAxisLogScale;
256      if (chart.Series.Any(x => x.Enabled && x.YAxisType == AxisType.Secondary && (x.Points.Count == 0 || x.Points.Any(y => y.YValues.Min() <= 0))))
257        area.AxisY2.IsLogarithmic = false;
258      else area.AxisY2.IsLogarithmic = Content.VisualProperties.SecondYAxisLogScale;
259
260      area.RecalculateAxesScale();
261      area.AxisX.IsMarginVisible = false;
262      area.AxisX2.IsMarginVisible = false;
263
264      if (!Content.VisualProperties.XAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.XAxisMinimumFixedValue)) area.AxisX.Minimum = Content.VisualProperties.XAxisMinimumFixedValue;
265      if (!Content.VisualProperties.XAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.XAxisMaximumFixedValue)) area.AxisX.Maximum = Content.VisualProperties.XAxisMaximumFixedValue;
266      if (!Content.VisualProperties.SecondXAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMinimumFixedValue)) area.AxisX2.Minimum = Content.VisualProperties.SecondXAxisMinimumFixedValue;
267      if (!Content.VisualProperties.SecondXAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondXAxisMaximumFixedValue)) area.AxisX2.Maximum = Content.VisualProperties.SecondXAxisMaximumFixedValue;
268      if (!Content.VisualProperties.YAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.YAxisMinimumFixedValue)) area.AxisY.Minimum = Content.VisualProperties.YAxisMinimumFixedValue;
269      if (!Content.VisualProperties.YAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.YAxisMaximumFixedValue)) area.AxisY.Maximum = Content.VisualProperties.YAxisMaximumFixedValue;
270      if (!Content.VisualProperties.SecondYAxisMinimumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMinimumFixedValue)) area.AxisY2.Minimum = Content.VisualProperties.SecondYAxisMinimumFixedValue;
271      if (!Content.VisualProperties.SecondYAxisMaximumAuto && !double.IsNaN(Content.VisualProperties.SecondYAxisMaximumFixedValue)) area.AxisY2.Maximum = Content.VisualProperties.SecondYAxisMaximumFixedValue;
272      if (area.AxisX.Minimum >= area.AxisX.Maximum) area.AxisX.Maximum = area.AxisX.Minimum + 1;
273      if (area.AxisX2.Minimum >= area.AxisX2.Maximum) area.AxisX2.Maximum = area.AxisX2.Minimum + 1;
274      if (area.AxisY.Minimum >= area.AxisY.Maximum) area.AxisY.Maximum = area.AxisY.Minimum + 1;
275      if (area.AxisY2.Minimum >= area.AxisY2.Maximum) area.AxisY2.Maximum = area.AxisY2.Minimum + 1;
276    }
277
278    /// <summary>
279    /// Set the Y Cursor interval to visible points of enabled series.
280    /// </summary>
281    protected virtual void UpdateYCursorInterval() {
282      double interestingValuesRange = (
283        from series in chart.Series
284        where series.Enabled
285        let values = (from point in series.Points
286                      where !point.IsEmpty
287                      select point.YValues[0]).DefaultIfEmpty(1.0)
288        let range = values.Max() - values.Min()
289        where range > 0.0
290        select range
291        ).DefaultIfEmpty(1.0).Min();
292
293      double digits = (int)Math.Log10(interestingValuesRange) - 3;
294      double yZoomInterval = Math.Pow(10, digits);
295      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
296    }
297
298
299    /// <summary>
300    /// Remove the corresponding series for a certain DataRow.
301    /// </summary>
302    /// <param name="row">DataRow which series should be removed.</param>
303    protected virtual void RemoveDataRow(IndexedDataRow<T> row) {
304      if (chart.Series.All(x => x.Name != row.Name)) return;
305      Series series = chart.Series[row.Name];
306      chart.Series.Remove(series);
307      if (invisibleSeries.Contains(series))
308        invisibleSeries.Remove(series);
309      RecalculateAxesScale(chart.ChartAreas[0]);
310    }
311
312    #region Event Handlers
313    #region Content Event Handlers
314    protected override void Content_NameChanged(object sender, EventArgs e) {
315      if (InvokeRequired)
316        Invoke(new EventHandler(Content_NameChanged), sender, e);
317      else {
318        chart.Titles[0].Text = Content.Name;
319        base.Content_NameChanged(sender, e);
320      }
321    }
322    private void Content_VisualPropertiesChanged(object sender, EventArgs e) {
323      if (InvokeRequired)
324        Invoke(new EventHandler(Content_VisualPropertiesChanged), sender, e);
325      else {
326        ConfigureChartArea(chart.ChartAreas[0]);
327        RecalculateAxesScale(chart.ChartAreas[0]); // axes min/max could have changed
328      }
329    }
330    #endregion
331    #region Rows Event Handlers
332    private void Rows_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
333      if (InvokeRequired)
334        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsAdded), sender, e);
335      else {
336        foreach (var row in e.Items) {
337          AddDataRow(row);
338          RegisterDataRowEvents(row);
339        }
340      }
341    }
342    private void Rows_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
343      if (InvokeRequired)
344        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsRemoved), sender, e);
345      else {
346        foreach (var row in e.Items) {
347          DeregisterDataRowEvents(row);
348          RemoveDataRow(row);
349        }
350      }
351    }
352    private void Rows_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
353      if (InvokeRequired)
354        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_ItemsReplaced), sender, e);
355      else {
356        foreach (var row in e.OldItems) {
357          DeregisterDataRowEvents(row);
358          RemoveDataRow(row);
359        }
360        foreach (var row in e.Items) {
361          AddDataRow(row);
362          RegisterDataRowEvents(row);
363        }
364      }
365    }
366    private void Rows_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedDataRow<T>> e) {
367      if (InvokeRequired)
368        Invoke(new CollectionItemsChangedEventHandler<IndexedDataRow<T>>(Rows_CollectionReset), sender, e);
369      else {
370        foreach (var row in e.OldItems) {
371          DeregisterDataRowEvents(row);
372          RemoveDataRow(row);
373        }
374        foreach (var row in e.Items) {
375          AddDataRow(row);
376          RegisterDataRowEvents(row);
377        }
378      }
379    }
380    #endregion
381    #region Row Event Handlers
382    private void Row_VisualPropertiesChanged(object sender, EventArgs e) {
383      if (InvokeRequired)
384        Invoke(new EventHandler(Row_VisualPropertiesChanged), sender, e);
385      else {
386        var row = (IndexedDataRow<T>)sender;
387        Series series = chart.Series[row.Name];
388        series.Points.Clear();
389        ConfigureSeries(series, row);
390        FillSeriesWithRowValues(series, row);
391        RecalculateAxesScale(chart.ChartAreas[0]);
392      }
393    }
394    private void Row_NameChanged(object sender, EventArgs e) {
395      if (InvokeRequired)
396        Invoke(new EventHandler(Row_NameChanged), sender, e);
397      else {
398        var row = (IndexedDataRow<T>)sender;
399        chart.Series[row.Name].Name = row.Name;
400      }
401    }
402    #endregion
403    #region Values Event Handlers
404    private void Values_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
405      if (InvokeRequired)
406        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsAdded), sender, e);
407      else {
408        IndexedDataRow<T> row = null;
409        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, 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        } else AddDataRow((IndexedDataRow<T>)sender);
419      }
420    }
421    private void Values_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
422      if (InvokeRequired)
423        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsRemoved), sender, e);
424      else {
425        IndexedDataRow<T> row = null;
426        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
427        if (row != null) {
428          if (row.Values.Count == 0) {
429            RemoveDataRow(row);
430          } else {
431            Series rowSeries = chart.Series[row.Name];
432            if (!invisibleSeries.Contains(rowSeries)) {
433              rowSeries.Points.Clear();
434              FillSeriesWithRowValues(rowSeries, row);
435              RecalculateAxesScale(chart.ChartAreas[0]);
436              UpdateYCursorInterval();
437            }
438          }
439        }
440      }
441    }
442    private void Values_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
443      if (InvokeRequired)
444        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsReplaced), sender, e);
445      else {
446        IndexedDataRow<T> row = null;
447        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
448        if (row != null) {
449          if (row.Values.Count == 0) {
450            RemoveDataRow(row);
451          } else {
452            Series rowSeries = chart.Series[row.Name];
453            if (!invisibleSeries.Contains(rowSeries)) {
454              if (row.VisualProperties.ChartType == DataRowVisualProperties.DataRowChartType.Histogram) {
455                rowSeries.Points.Clear();
456                FillSeriesWithRowValues(rowSeries, row);
457              } else {
458                foreach (IndexedItem<Tuple<T, double>> item in e.Items) {
459                  rowSeries.Points[item.Index].SetValueXY(item.Value.Item1, item.Value.Item2);
460                }
461              }
462              RecalculateAxesScale(chart.ChartAreas[0]);
463              UpdateYCursorInterval();
464            }
465          }
466        }
467      }
468    }
469    private void Values_ItemsMoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
470      if (InvokeRequired)
471        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_ItemsMoved), sender, e);
472      else {
473        IndexedDataRow<T> row = null;
474        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
475        if (row != null) {
476          Series rowSeries = chart.Series[row.Name];
477          if (!invisibleSeries.Contains(rowSeries)) {
478            rowSeries.Points.Clear();
479            FillSeriesWithRowValues(rowSeries, row);
480            RecalculateAxesScale(chart.ChartAreas[0]);
481            UpdateYCursorInterval();
482          }
483        }
484      }
485    }
486
487    private void Values_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<Tuple<T, double>>> e) {
488      if (InvokeRequired)
489        Invoke(new CollectionItemsChangedEventHandler<IndexedItem<Tuple<T, double>>>(Values_CollectionReset), sender, e);
490      else {
491        IndexedDataRow<T> row = null;
492        valuesRowsTable.TryGetValue((IObservableList<Tuple<T, double>>)sender, out row);
493        if (row != null) {
494          if (row.Values.Count == 0) {
495            RemoveDataRow(row);
496          } else {
497            Series rowSeries = chart.Series[row.Name];
498            if (!invisibleSeries.Contains(rowSeries)) {
499              rowSeries.Points.Clear();
500              FillSeriesWithRowValues(rowSeries, row);
501              RecalculateAxesScale(chart.ChartAreas[0]);
502              UpdateYCursorInterval();
503            }
504          }
505        }
506      }
507    }
508    #endregion
509    #endregion
510
511    #region Chart Event Handlers
512    private void chart_MouseDown(object sender, MouseEventArgs e) {
513      HitTestResult result = chart.HitTest(e.X, e.Y);
514      if (result.ChartElementType == ChartElementType.LegendItem) {
515        ToggleSeriesVisible(result.Series);
516      }
517    }
518    private void chart_MouseMove(object sender, MouseEventArgs e) {
519      HitTestResult result = chart.HitTest(e.X, e.Y);
520      if (result.ChartElementType == ChartElementType.LegendItem)
521        this.Cursor = Cursors.Hand;
522      else
523        this.Cursor = Cursors.Default;
524    }
525    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
526      foreach (LegendItem legendItem in e.LegendItems) {
527        var series = chart.Series[legendItem.SeriesName];
528        if (series != null) {
529          bool seriesIsInvisible = invisibleSeries.Contains(series);
530          foreach (LegendCell cell in legendItem.Cells) {
531            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
532          }
533        }
534      }
535    }
536    #endregion
537
538    private void ToggleSeriesVisible(Series series) {
539      if (!invisibleSeries.Contains(series)) {
540        series.Points.Clear();
541        invisibleSeries.Add(series);
542      } else {
543        invisibleSeries.Remove(series);
544        if (Content != null) {
545
546          var row = (from r in Content.Rows
547                     where r.Name == series.Name
548                     select r).Single();
549          FillSeriesWithRowValues(series, row);
550          this.chart.Legends[series.Legend].ForeColor = Color.Black;
551          RecalculateAxesScale(chart.ChartAreas[0]);
552          UpdateYCursorInterval();
553        }
554      }
555    }
556
557    private void FillSeriesWithRowValues(Series series, IndexedDataRow<T> row) {
558      for (int i = 0; i < row.Values.Count; i++) {
559        var value = row.Values[i];
560        var point = new DataPoint();
561        point.SetValueXY(value.Item1, value.Item2);
562        if (i == row.Values.Count - 1) {
563          point.Label = series.Name;
564          point.MarkerStyle = MarkerStyle.Cross;
565          point.MarkerSize = 15;
566          point.MarkerBorderWidth = 1;
567        }
568        series.Points.Add(point);
569      }
570    }
571
572    #region Helpers
573    protected void RemoveCustomPropertyIfExists(Series series, string property) {
574      if (series.IsCustomPropertySet(property)) series.DeleteCustomProperty(property);
575    }
576
577    private ChartDashStyle ConvertLineStyle(DataRowVisualProperties.DataRowLineStyle dataRowLineStyle) {
578      switch (dataRowLineStyle) {
579        case DataRowVisualProperties.DataRowLineStyle.Dash:
580          return ChartDashStyle.Dash;
581        case DataRowVisualProperties.DataRowLineStyle.DashDot:
582          return ChartDashStyle.DashDot;
583        case DataRowVisualProperties.DataRowLineStyle.DashDotDot:
584          return ChartDashStyle.DashDotDot;
585        case DataRowVisualProperties.DataRowLineStyle.Dot:
586          return ChartDashStyle.Dot;
587        case DataRowVisualProperties.DataRowLineStyle.NotSet:
588          return ChartDashStyle.NotSet;
589        case DataRowVisualProperties.DataRowLineStyle.Solid:
590          return ChartDashStyle.Solid;
591        default:
592          return ChartDashStyle.NotSet;
593      }
594    }
595
596    /// <summary>
597    /// Determines whether a double value can be displayed (converted to Decimal and not an NaN).
598    /// </summary>
599    /// <param name="x">The number to check.</param>
600    /// <returns><code>true</code> if the value can be safely shwon in the chart,
601    /// <code>false</code> otherwise.</returns>
602    protected static bool IsInvalidValue(double x) {
603      return double.IsNaN(x) || x < (double)decimal.MinValue || x > (double)decimal.MaxValue;
604    }
605    #endregion
606  }
607}
Note: See TracBrowser for help on using the repository browser.