Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed copying of values from the StringConvertibleMatrixView (ticket #1230).

File size: 19.2 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) && Content.RowNames.Count() > 0;
283      bool addColumnNames = dataGridView.AreAllCellsSelected(false) && Content.ColumnNames.Count() > 0;
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            s.Append('\t');
313          }
314
315          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
316        }
317        s.Remove(s.Length - 1, 1); //remove last tab
318        s.Append(Environment.NewLine);
319      }
320      Clipboard.SetText(s.ToString());
321    }
322
323    private void PasteValuesToDataGridView() {
324      string[,] values = SplitClipboardString(Clipboard.GetText());
325      int rowIndex = 0;
326      int columnIndex = 0;
327      if (dataGridView.CurrentCell != null) {
328        rowIndex = dataGridView.CurrentCell.RowIndex;
329        columnIndex = dataGridView.CurrentCell.ColumnIndex;
330      }
331
332      for (int row = 0; row < values.GetLength(1); row++) {
333        if (row + rowIndex >= Content.Rows)
334          Content.Rows = Content.Rows + 1;
335        for (int col = 0; col < values.GetLength(0); col++) {
336          if (col + columnIndex >= Content.Columns)
337            Content.Columns = Content.Columns + 1;
338          Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
339        }
340      }
341      ClearSorting();
342    }
343    private string[,] SplitClipboardString(string clipboardText) {
344      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
345      string[,] values = null;
346      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
347      string[] cells;
348      for (int i = 0; i < lines.Length; i++) {
349        cells = lines[i].Split('\t');
350        if (values == null)
351          values = new string[cells.Length, lines.Length];
352        for (int j = 0; j < cells.Length; j++)
353          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
354      }
355      return values;
356    }
357
358    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
359      if (Content != null) {
360        if (e.Button == MouseButtons.Left && Content.SortableView) {
361          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
362          SortOrder newSortOrder = SortOrder.Ascending;
363          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
364            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
365            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
366            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
367          }
368
369          if (!addToSortedIndizes)
370            sortedColumnIndizes.Clear();
371
372          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
373            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
374            if (newSortOrder != SortOrder.None)
375              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
376            else
377              sortedColumnIndizes.RemoveAt(sortedIndex);
378          } else
379            if (newSortOrder != SortOrder.None)
380              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
381          Sort();
382        }
383      }
384    }
385
386    protected virtual void ClearSorting() {
387      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
388      sortedColumnIndizes.Clear();
389      UpdateSortGlyph();
390    }
391
392    private void Sort() {
393      virtualRowIndizes = Sort(sortedColumnIndizes);
394      UpdateSortGlyph();
395      UpdateRowHeaders();
396      dataGridView.Invalidate();
397    }
398    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
399      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
400      if (sortedColumns.Count() != 0) {
401        rowComparer.SortedIndizes = sortedColumns;
402        rowComparer.Matrix = Content;
403        Array.Sort(newSortedIndex, rowComparer);
404      }
405      return newSortedIndex;
406    }
407    private void UpdateSortGlyph() {
408      foreach (DataGridViewColumn col in this.dataGridView.Columns)
409        col.HeaderCell.SortGlyphDirection = SortOrder.None;
410      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
411        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
412    }
413    #endregion
414
415    public class RowComparer : IComparer<int> {
416      public RowComparer() {
417      }
418
419      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
420      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
421        get { return this.sortedIndizes; }
422        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
423      }
424      private IStringConvertibleMatrix matrix;
425      public IStringConvertibleMatrix Matrix {
426        get { return this.matrix; }
427        set { this.matrix = value; }
428      }
429
430      public int Compare(int x, int y) {
431        int result = 0;
432        double double1, double2;
433        DateTime dateTime1, dateTime2;
434        TimeSpan timeSpan1, timeSpan2;
435        string string1, string2;
436
437        if (matrix == null)
438          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
439        if (sortedIndizes == null)
440          return 0;
441
442        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
443          string1 = matrix.GetValue(x, pair.Key);
444          string2 = matrix.GetValue(y, pair.Key);
445          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
446            result = double1.CompareTo(double2);
447          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
448            result = dateTime1.CompareTo(dateTime2);
449          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
450            result = timeSpan1.CompareTo(timeSpan2);
451          else {
452            if (string1 != null)
453              result = string1.CompareTo(string2);
454            else if (string2 != null)
455              result = string2.CompareTo(string1) * -1;
456          }
457          if (pair.Value == SortOrder.Descending)
458            result *= -1;
459          if (result != 0)
460            return result;
461        }
462        return result;
463      }
464    }
465
466    private void dataGridView_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) {
467      if (Content == null) return;
468      if (e.Button == MouseButtons.Right && Content.ColumnNames.Count() != 0)
469        contextMenu.Show(MousePosition);
470    }
471    private void ShowHideColumns_Click(object sender, EventArgs e) {
472      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
473    }
474  }
475}
Note: See TracBrowser for help on using the repository browser.