Free cookie consent management tool by TermsFeed Policy Generator

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

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

corrected StringConvertibleMatrixView (ticket #1134)

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