Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.1/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 5545

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

Corrected coloring of runs in RunCollectionTabularView (ticket #1213).

File size: 19.1 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.Collections.Generic;
24using System.ComponentModel;
25using System.Linq;
26using System.Text;
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    private int[] virtualRowIndizes;
37    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
38    private RowComparer rowComparer;
39
40    public new IStringConvertibleMatrix Content {
41      get { return (IStringConvertibleMatrix)base.Content; }
42      set { base.Content = value; }
43    }
44
45    public override bool ReadOnly {
46      get {
47        if ((Content != null) && Content.ReadOnly) return true;
48        return base.ReadOnly;
49      }
50      set { base.ReadOnly = value; }
51    }
52
53    public StringConvertibleMatrixView() {
54      InitializeComponent();
55      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
56      errorProvider.SetIconPadding(rowsTextBox, 2);
57      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
58      errorProvider.SetIconPadding(columnsTextBox, 2);
59      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
60      rowComparer = new RowComparer();
61    }
62
63    protected override void DeregisterContentEvents() {
64      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
65      Content.Reset -= new EventHandler(Content_Reset);
66      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
67      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
68      base.DeregisterContentEvents();
69    }
70    protected override void RegisterContentEvents() {
71      base.RegisterContentEvents();
72      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
73      Content.Reset += new EventHandler(Content_Reset);
74      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
75      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
76    }
77
78    protected override void OnContentChanged() {
79      base.OnContentChanged();
80      if (Content == null) {
81        rowsTextBox.Text = "";
82        columnsTextBox.Text = "";
83        dataGridView.Rows.Clear();
84        dataGridView.Columns.Clear();
85        virtualRowIndizes = new int[0];
86      } else
87        UpdateData();
88    }
89
90    protected override void SetEnabledStateOfControls() {
91      base.SetEnabledStateOfControls();
92      rowsTextBox.Enabled = Content != null;
93      columnsTextBox.Enabled = Content != null;
94      dataGridView.Enabled = Content != null;
95      rowsTextBox.ReadOnly = ReadOnly;
96      columnsTextBox.ReadOnly = ReadOnly;
97      dataGridView.ReadOnly = ReadOnly;
98    }
99
100    private void UpdateData() {
101
102      rowsTextBox.Text = Content.Rows.ToString();
103      rowsTextBox.Enabled = true;
104      columnsTextBox.Text = Content.Columns.ToString();
105      columnsTextBox.Enabled = true;
106      //DataGridViews with rows but no columns are not allowed !
107      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
108        Content.Rows = dataGridView.RowCount;
109      else
110        dataGridView.RowCount = Content.Rows;
111      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
112        Content.Columns = dataGridView.ColumnCount;
113      else
114        dataGridView.ColumnCount = Content.Columns;
115      ClearSorting();
116
117      UpdateColumnHeaders();
118      UpdateRowHeaders();
119      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
120      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
121      dataGridView.Enabled = true;
122    }
123
124    protected void UpdateColumnHeaders() {
125      for (int i = 0; i < dataGridView.ColumnCount; i++) {
126        if (Content.ColumnNames.Count() != 0)
127          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
128        else
129          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
130      }
131    }
132    protected void UpdateRowHeaders() {
133      int index = dataGridView.FirstDisplayedScrollingRowIndex;
134      if (index == -1) index = 0;
135      int updatedRows = 0;
136      int count = dataGridView.DisplayedRowCount(true);
137
138      while (updatedRows < count) {
139        if (Content.RowNames.Count() != 0)
140          dataGridView.Rows[index].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[index]);
141        else
142          dataGridView.Rows[index].HeaderCell.Value = "Row " + (index + 1);
143        if (dataGridView.Rows[index].Visible)
144          updatedRows++;
145        index++;
146      }
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    #region TextBox Events
175    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
176      if (ReadOnly || Locked)
177        return;
178      int i = 0;
179      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
180        e.Cancel = true;
181        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
182        rowsTextBox.SelectAll();
183      }
184    }
185    private void rowsTextBox_Validated(object sender, EventArgs e) {
186      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
187      errorProvider.SetError(rowsTextBox, string.Empty);
188    }
189    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
190      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
191        rowsLabel.Focus();  // set focus on label to validate data
192      if (e.KeyCode == Keys.Escape) {
193        rowsTextBox.Text = Content.Rows.ToString();
194        rowsLabel.Focus();  // set focus on label to validate data
195      }
196    }
197    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
198      if (ReadOnly || Locked)
199        return;
200      int i = 0;
201      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
202        e.Cancel = true;
203        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
204        columnsTextBox.SelectAll();
205      }
206    }
207    private void columnsTextBox_Validated(object sender, EventArgs e) {
208      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
209      errorProvider.SetError(columnsTextBox, string.Empty);
210    }
211    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
212      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
213        columnsLabel.Focus();  // set focus on label to validate data
214      if (e.KeyCode == Keys.Escape) {
215        columnsTextBox.Text = Content.Columns.ToString();
216        columnsLabel.Focus();  // set focus on label to validate data
217      }
218    }
219    #endregion
220
221    #region DataGridView Events
222    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
223      if (!dataGridView.ReadOnly) {
224        string errorMessage;
225        if (Content != null && !Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
226          e.Cancel = true;
227          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
228        }
229      }
230    }
231    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
232      if (!dataGridView.ReadOnly) {
233        string value = e.Value.ToString();
234        int rowIndex = virtualRowIndizes[e.RowIndex];
235        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
236        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
237      }
238    }
239    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
240      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
241    }
242    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
243      if (Content != null && e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
244        int rowIndex = virtualRowIndizes[e.RowIndex];
245        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
246      }
247    }
248
249    private void dataGridView_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {
250      this.UpdateRowHeaders();
251    }
252    private void dataGridView_Resize(object sender, EventArgs e) {
253      this.UpdateRowHeaders();
254    }
255
256    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
257      if (!ReadOnly && e.Control && e.KeyCode == Keys.V)
258        PasteValuesToDataGridView();
259      else if (e.Control && e.KeyCode == Keys.C)
260        CopyValuesFromDataGridView();
261    }
262
263    private void CopyValuesFromDataGridView() {
264      if (dataGridView.SelectedCells.Count == 0) return;
265      StringBuilder s = new StringBuilder();
266      int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
267      int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
268      int minColIndex = dataGridView.SelectedCells[0].ColumnIndex;
269      int maxColIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].ColumnIndex;
270
271      if (minRowIndex > maxRowIndex) {
272        int temp = minRowIndex;
273        minRowIndex = maxRowIndex;
274        maxRowIndex = temp;
275      }
276      if (minColIndex > maxColIndex) {
277        int temp = minColIndex;
278        minColIndex = maxColIndex;
279        maxColIndex = temp;
280      }
281
282      bool addRowNames = dataGridView.AreAllCellsSelected(false);
283      bool addColumnNames = dataGridView.AreAllCellsSelected(false);
284
285      //add colum names
286      if (addColumnNames) {
287        if (addRowNames)
288          s.Append('\t');
289
290        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
291        while (column != null) {
292          s.Append(column.HeaderText);
293          s.Append('\t');
294          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
295        }
296        s.Remove(s.Length - 1, 1); //remove last tab
297        s.Append(Environment.NewLine);
298      }
299
300      for (int i = minRowIndex; i <= maxRowIndex; i++) {
301        int rowIndex = this.virtualRowIndizes[i];
302        if (addRowNames) {
303          s.Append(Content.RowNames.ElementAt(rowIndex));
304          s.Append('\t');
305        }
306
307        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
308        while (column != null) {
309          DataGridViewCell cell = dataGridView[column.Index, i];
310          if (cell.Selected) {
311            s.Append(Content.GetValue(rowIndex, column.Index));
312          }
313          s.Append('\t');
314          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
315        }
316        s.Remove(s.Length - 1, 1); //remove last tab
317        s.Append(Environment.NewLine);
318      }
319      Clipboard.SetText(s.ToString());
320    }
321
322    private void PasteValuesToDataGridView() {
323      string[,] values = SplitClipboardString(Clipboard.GetText());
324      int rowIndex = 0;
325      int columnIndex = 0;
326      if (dataGridView.CurrentCell != null) {
327        rowIndex = dataGridView.CurrentCell.RowIndex;
328        columnIndex = dataGridView.CurrentCell.ColumnIndex;
329      }
330
331      for (int row = 0; row < values.GetLength(1); row++) {
332        if (row + rowIndex >= Content.Rows)
333          Content.Rows = Content.Rows + 1;
334        for (int col = 0; col < values.GetLength(0); col++) {
335          if (col + columnIndex >= Content.Columns)
336            Content.Columns = Content.Columns + 1;
337          Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
338        }
339      }
340      ClearSorting();
341    }
342    private string[,] SplitClipboardString(string clipboardText) {
343      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
344      string[,] values = null;
345      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
346      string[] cells;
347      for (int i = 0; i < lines.Length; i++) {
348        cells = lines[i].Split('\t');
349        if (values == null)
350          values = new string[cells.Length, lines.Length];
351        for (int j = 0; j < cells.Length; j++)
352          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
353      }
354      return values;
355    }
356
357    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
358      if (Content != null) {
359        if (e.Button == MouseButtons.Left && Content.SortableView) {
360          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
361          SortOrder newSortOrder = SortOrder.Ascending;
362          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
363            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
364            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
365            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
366          }
367
368          if (!addToSortedIndizes)
369            sortedColumnIndizes.Clear();
370
371          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
372            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
373            if (newSortOrder != SortOrder.None)
374              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
375            else
376              sortedColumnIndizes.RemoveAt(sortedIndex);
377          } else
378            if (newSortOrder != SortOrder.None)
379              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
380          Sort();
381        }
382      }
383    }
384
385    protected virtual void ClearSorting() {
386      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
387      sortedColumnIndizes.Clear();
388      UpdateSortGlyph();
389    }
390
391    private void Sort() {
392      virtualRowIndizes = Sort(sortedColumnIndizes);
393      UpdateSortGlyph();
394      UpdateRowHeaders();
395      dataGridView.Invalidate();
396    }
397    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
398      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
399      if (sortedColumns.Count() != 0) {
400        rowComparer.SortedIndizes = sortedColumns;
401        rowComparer.Matrix = Content;
402        Array.Sort(newSortedIndex, rowComparer);
403      }
404      return newSortedIndex;
405    }
406    private void UpdateSortGlyph() {
407      foreach (DataGridViewColumn col in this.dataGridView.Columns)
408        col.HeaderCell.SortGlyphDirection = SortOrder.None;
409      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
410        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
411    }
412    #endregion
413
414    public class RowComparer : IComparer<int> {
415      public RowComparer() {
416      }
417
418      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
419      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
420        get { return this.sortedIndizes; }
421        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
422      }
423      private IStringConvertibleMatrix matrix;
424      public IStringConvertibleMatrix Matrix {
425        get { return this.matrix; }
426        set { this.matrix = value; }
427      }
428
429      public int Compare(int x, int y) {
430        int result = 0;
431        double double1, double2;
432        DateTime dateTime1, dateTime2;
433        TimeSpan timeSpan1, timeSpan2;
434        string string1, string2;
435
436        if (matrix == null)
437          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
438        if (sortedIndizes == null)
439          return 0;
440
441        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
442          string1 = matrix.GetValue(x, pair.Key);
443          string2 = matrix.GetValue(y, pair.Key);
444          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
445            result = double1.CompareTo(double2);
446          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
447            result = dateTime1.CompareTo(dateTime2);
448          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
449            result = timeSpan1.CompareTo(timeSpan2);
450          else {
451            if (string1 != null)
452              result = string1.CompareTo(string2);
453            else if (string2 != null)
454              result = string2.CompareTo(string1) * -1;
455          }
456          if (pair.Value == SortOrder.Descending)
457            result *= -1;
458          if (result != 0)
459            return result;
460        }
461        return result;
462      }
463    }
464
465    private void dataGridView_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) {
466      if (Content == null) return;
467      if (e.Button == MouseButtons.Right && Content.ColumnNames.Count() != 0)
468        contextMenu.Show(MousePosition);
469    }
470    private void ShowHideColumns_Click(object sender, EventArgs e) {
471      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
472    }
473  }
474}
Note: See TracBrowser for help on using the repository browser.