Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 3346

Last change on this file since 3346 was 3346, checked in by mkommend, 14 years ago

implemented comments from swa (ticket #968)

File size: 14.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.ComponentModel;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31
32namespace HeuristicLab.Data.Views {
33  [View("StringConvertibleMatrix View")]
34  [Content(typeof(IStringConvertibleMatrix), true)]
35  public partial class StringConvertibleMatrixView : AsynchronousContentView {
36    public new IStringConvertibleMatrix Content {
37      get { return (IStringConvertibleMatrix)base.Content; }
38      set { base.Content = value; }
39    }
40
41    private int[] virtualRowIndizes;
42    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
43    RowComparer rowComparer;
44
45    public StringConvertibleMatrixView() {
46      InitializeComponent();
47      Caption = "StringConvertibleMatrix View";
48      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
49      errorProvider.SetIconPadding(rowsTextBox, 2);
50      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
51      errorProvider.SetIconPadding(columnsTextBox, 2);
52      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
53      rowComparer = new RowComparer();
54    }
55    public StringConvertibleMatrixView(IStringConvertibleMatrix content)
56      : this() {
57      Content = content;
58    }
59
60    protected override void DeregisterContentEvents() {
61      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
62      Content.Reset -= new EventHandler(Content_Reset);
63      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
64      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
65      Content.ReadOnlyViewChanged -= new EventHandler(Content_ReadOnlyViewChanged);
66      base.DeregisterContentEvents();
67    }
68
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
72      Content.Reset += new EventHandler(Content_Reset);
73      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
74      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
75      Content.ReadOnlyViewChanged += new EventHandler(Content_ReadOnlyViewChanged);
76    }
77
78
79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
82        Caption = "StringConvertibleMatrix View";
83        rowsTextBox.Text = "";
84        rowsTextBox.Enabled = false;
85        columnsTextBox.Text = "";
86        columnsTextBox.Enabled = false;
87        dataGridView.Rows.Clear();
88        dataGridView.Columns.Clear();
89        dataGridView.Enabled = false;
90        virtualRowIndizes = new int[0];
91      } else {
92        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
93        UpdateReadOnlyControls();
94        UpdateData();
95      }
96    }
97
98    private void UpdateData() {
99      sortedColumnIndizes.Clear();
100      Sort();
101      rowsTextBox.Text = Content.Rows.ToString();
102      rowsTextBox.Enabled = true;
103      columnsTextBox.Text = Content.Columns.ToString();
104      columnsTextBox.Enabled = true;
105      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
106      //DataGridViews with Rows but no columns are not allowed !
107      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnlyView)
108        Content.Rows = dataGridView.RowCount;
109      else
110        dataGridView.RowCount = Content.Rows;
111      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnlyView)
112        Content.Columns = dataGridView.ColumnCount;
113      else
114        dataGridView.ColumnCount = Content.Columns;
115
116      UpdateRowHeaders();
117      UpdateColumnHeaders();
118      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
119      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
120      dataGridView.Enabled = true;
121    }
122
123    private void UpdateColumnHeaders() {
124      for (int i = 0; i < Content.Columns; i++) {
125        if (Content.ColumnNames.Count() != 0)
126          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
127        else
128          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
129      }
130      dataGridView.Invalidate();
131    }
132
133    private void UpdateRowHeaders() {
134      for (int i = dataGridView.FirstDisplayedScrollingRowIndex; i < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(true); i++) {
135        if (Content.RowNames.Count() != 0)
136          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(i);
137        else
138          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
139      }
140      dataGridView.Invalidate();
141    }
142
143    private void UpdateReadOnlyControls() {
144      dataGridView.ReadOnly = Content.ReadOnlyView;
145      rowsTextBox.ReadOnly = Content.ReadOnlyView;
146      columnsTextBox.ReadOnly = Content.ReadOnlyView;
147    }
148
149    private void Content_RowNamesChanged(object sender, EventArgs e) {
150      if (InvokeRequired)
151        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
152      else
153        UpdateRowHeaders();
154    }
155    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
156      if (InvokeRequired)
157        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
158      else
159        UpdateColumnHeaders();
160    }
161    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
162      if (InvokeRequired)
163        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
164      else
165        dataGridView.InvalidateCell(e.Value2, e.Value);
166    }
167    private void Content_Reset(object sender, EventArgs e) {
168      if (InvokeRequired)
169        Invoke(new EventHandler(Content_Reset), sender, e);
170      else
171        UpdateData();
172    }
173
174    private void Content_ReadOnlyViewChanged(object sender, EventArgs e) {
175      if (InvokeRequired)
176        Invoke(new EventHandler(Content_ReadOnlyViewChanged), sender, e);
177      else
178        UpdateReadOnlyControls();
179    }
180
181    #region TextBox Events
182    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
183      int i = 0;
184      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
185        e.Cancel = true;
186        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
187        rowsTextBox.SelectAll();
188      }
189    }
190    private void rowsTextBox_Validated(object sender, EventArgs e) {
191      int textBoxValue = int.Parse(rowsTextBox.Text);
192      if (textBoxValue != Content.Rows)
193        Content.Rows = textBoxValue;
194      errorProvider.SetError(rowsTextBox, string.Empty);
195    }
196    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
197      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
198        rowsLabel.Focus();  // set focus on label to validate data
199      if (e.KeyCode == Keys.Escape) {
200        rowsTextBox.Text = Content.Rows.ToString();
201        rowsLabel.Focus();  // set focus on label to validate data
202      }
203    }
204    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
205      int i = 0;
206      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
207        e.Cancel = true;
208        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
209        columnsTextBox.SelectAll();
210      }
211    }
212    private void columnsTextBox_Validated(object sender, EventArgs e) {
213      int textBoxValue = int.Parse(columnsTextBox.Text);
214      if (textBoxValue != Content.Columns)
215        Content.Columns = textBoxValue;
216      errorProvider.SetError(columnsTextBox, string.Empty);
217    }
218    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
219      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
220        columnsLabel.Focus();  // set focus on label to validate data
221      if (e.KeyCode == Keys.Escape) {
222        columnsTextBox.Text = Content.Columns.ToString();
223        columnsLabel.Focus();  // set focus on label to validate data
224      }
225    }
226    #endregion
227
228    #region DataGridView Events
229    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
230      if (!dataGridView.ReadOnly) {
231        string errorMessage;
232        if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
233          e.Cancel = true;
234          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
235        }
236      }
237    }
238    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
239      if (!dataGridView.ReadOnly) {
240        string value = e.Value.ToString();
241        int rowIndex = virtualRowIndizes[e.RowIndex];
242        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
243        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
244      }
245    }
246    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
247      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
248    }
249    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
250      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
251        int rowIndex = virtualRowIndizes[e.RowIndex];
252        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
253      }
254    }
255    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
256      UpdateRowHeaders();
257    }
258    private void dataGridView_Resize(object sender, EventArgs e) {
259      UpdateRowHeaders();
260    }
261
262    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
263      if (Content != null) {
264        if (e.Button == MouseButtons.Left && Content.SortableView) {
265          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
266          SortOrder newSortOrder = SortOrder.Ascending;
267          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
268            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
269            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
270            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
271          }
272
273          if (!addToSortedIndizes)
274            sortedColumnIndizes.Clear();
275
276          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
277            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
278            if (newSortOrder != SortOrder.None)
279              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
280            else
281              sortedColumnIndizes.RemoveAt(sortedIndex);
282          } else
283            if (newSortOrder != SortOrder.None)
284              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
285          Sort();
286        } else if (e.Button == MouseButtons.Right) {
287          if (Content.ColumnNames.Count() != 0)
288            contextMenu.Show(MousePosition);
289        }
290      }
291    }
292
293    private void Sort() {
294      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
295      if (sortedColumnIndizes.Count != 0) {
296        rowComparer.SortedIndizes = sortedColumnIndizes;
297        rowComparer.Matrix = Content;
298        Array.Sort(newSortedIndex, rowComparer);
299      }
300      virtualRowIndizes = newSortedIndex;
301      UpdateSortGlyph();
302      dataGridView.Invalidate();
303    }
304
305    private void UpdateSortGlyph() {
306      foreach (DataGridViewColumn col in this.dataGridView.Columns)
307        col.HeaderCell.SortGlyphDirection = SortOrder.None;
308      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
309        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
310    }
311    #endregion
312
313    public class RowComparer : IComparer<int> {
314      public RowComparer() {
315      }
316
317      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
318      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
319        get { return this.sortedIndizes; }
320        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
321      }
322      private IStringConvertibleMatrix matrix;
323      public IStringConvertibleMatrix Matrix {
324        get { return this.matrix; }
325        set { this.matrix = value; }
326      }
327
328      public int Compare(int x, int y) {
329        int result = 0;
330        double double1, double2;
331        DateTime dateTime1, dateTime2;
332        string string1, string2;
333
334        if (matrix == null)
335          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
336        if (sortedIndizes == null)
337          return 0;
338
339        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
340            string1 = matrix.GetValue(x, pair.Key);
341            string2 = matrix.GetValue(y, pair.Key);
342            if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
343              result = double1.CompareTo(double2);
344            else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
345              result = dateTime1.CompareTo(dateTime2);
346            else {
347              if (string1 != null)
348                result = string1.CompareTo(string2);
349              else if (string2 != null)
350                result = string2.CompareTo(string1) * -1;
351            }
352            if (pair.Value == SortOrder.Descending)
353              result *= -1;
354            if (result != 0)
355              return result;
356        }
357        return result;
358      }
359    }
360
361    private void ShowHideColumns_Click(object sender, EventArgs e) {
362      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
363    }
364  }
365}
Note: See TracBrowser for help on using the repository browser.