Free cookie consent management tool by TermsFeed Policy Generator

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

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

adapted the ColumnsVisibilityDialog and corrected copy and past support in the 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    protected 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      UpdateRowHeaders();
117      UpdateColumnHeaders();
118      dataGridView.Enabled = true;
119      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
120    }
121
122    private void UpdateColumnHeaders() {
123      for (int i = 0; i < dataGridView.ColumnCount; i++) {
124        if (Content.ColumnNames.Count() != 0)
125          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
126        else
127          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
128      }
129      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
130    }
131
132    private void UpdateRowHeaders() {
133      int firstDisplayedRowIndex = dataGridView.FirstDisplayedScrollingRowIndex;
134      if (firstDisplayedRowIndex == -1)
135        firstDisplayedRowIndex = 0;
136      int lastDisplaydRowIndex = firstDisplayedRowIndex + dataGridView.DisplayedRowCount(true);
137
138      for (int i = firstDisplayedRowIndex; i < lastDisplaydRowIndex; i++) {
139        if (Content.RowNames.Count() != 0)
140          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
141        else
142          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
143      }
144    }
145
146    private void Content_RowNamesChanged(object sender, EventArgs e) {
147      if (InvokeRequired)
148        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
149      else
150        UpdateRowHeaders();
151    }
152    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
155      else
156        UpdateColumnHeaders();
157    }
158    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
159      if (InvokeRequired)
160        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
161      else
162        dataGridView.InvalidateCell(e.Value2, e.Value);
163    }
164    private void Content_Reset(object sender, EventArgs e) {
165      if (InvokeRequired)
166        Invoke(new EventHandler(Content_Reset), sender, e);
167      else
168        UpdateData();
169    }
170
171    #region TextBox Events
172    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
173      if (ReadOnly || Locked)
174        return;
175      int i = 0;
176      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
177        e.Cancel = true;
178        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
179        rowsTextBox.SelectAll();
180      }
181    }
182    private void rowsTextBox_Validated(object sender, EventArgs e) {
183      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
184      errorProvider.SetError(rowsTextBox, string.Empty);
185    }
186    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
187      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
188        rowsLabel.Focus();  // set focus on label to validate data
189      if (e.KeyCode == Keys.Escape) {
190        rowsTextBox.Text = Content.Rows.ToString();
191        rowsLabel.Focus();  // set focus on label to validate data
192      }
193    }
194    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
195      if (ReadOnly || Locked)
196        return;
197      int i = 0;
198      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
199        e.Cancel = true;
200        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
201        columnsTextBox.SelectAll();
202      }
203    }
204    private void columnsTextBox_Validated(object sender, EventArgs e) {
205      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
206      errorProvider.SetError(columnsTextBox, string.Empty);
207    }
208    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
209      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
210        columnsLabel.Focus();  // set focus on label to validate data
211      if (e.KeyCode == Keys.Escape) {
212        columnsTextBox.Text = Content.Columns.ToString();
213        columnsLabel.Focus();  // set focus on label to validate data
214      }
215    }
216    #endregion
217
218    #region DataGridView Events
219    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
220      if (!dataGridView.ReadOnly) {
221        string errorMessage;
222        if (Content != null && !Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
223          e.Cancel = true;
224          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
225        }
226      }
227    }
228    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
229      if (!dataGridView.ReadOnly) {
230        string value = e.Value.ToString();
231        int rowIndex = virtualRowIndizes[e.RowIndex];
232        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
233        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
234      }
235    }
236    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
237      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
238    }
239    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
240      if (Content != null && e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
241        int rowIndex = virtualRowIndizes[e.RowIndex];
242        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
243      }
244    }
245
246    private void dataGridView_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {
247      this.UpdateRowHeaders();
248    }
249    private void dataGridView_Resize(object sender, EventArgs e) {
250      this.UpdateRowHeaders();
251    }
252
253    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
254      if (!ReadOnly && e.Control && e.KeyCode == Keys.V)
255        PasteValuesToDataGridView();
256      else if (e.Control && e.KeyCode == Keys.C)
257        CopyValuesFromDataGridView();
258    }
259
260    private void CopyValuesFromDataGridView() {
261      if (dataGridView.SelectedCells.Count == 0) return;
262      StringBuilder s = new StringBuilder();
263      int minRowIndex = dataGridView.SelectedCells[0].RowIndex;
264      int maxRowIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].RowIndex;
265      int minColIndex = dataGridView.SelectedCells[0].ColumnIndex;
266      int maxColIndex = dataGridView.SelectedCells[dataGridView.SelectedCells.Count - 1].ColumnIndex;
267
268      if (minRowIndex > maxRowIndex) {
269        int temp = minRowIndex;
270        minRowIndex = maxRowIndex;
271        maxRowIndex = temp;
272      }
273      if (minColIndex > maxColIndex) {
274        int temp = minColIndex;
275        minColIndex = maxColIndex;
276        maxColIndex = temp;
277      }
278
279      bool addColumnNames = Content.ColumnNames.Any() && minRowIndex == 0;
280      bool addRowNames = Content.RowNames.Any() && minColIndex == 0;
281
282      //add colum names
283      if (addColumnNames) {
284        if (addRowNames)
285          s.Append('\t');
286
287        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
288        while (column != null) {
289          s.Append(column.HeaderText);
290          s.Append('\t');
291          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
292        }
293        s.Remove(s.Length - 1, 1); //remove last tab
294        s.Append(Environment.NewLine);
295      }
296
297      for (int i = minRowIndex; i <= maxRowIndex; i++) {
298        int rowIndex = this.virtualRowIndizes[i];
299        if (addRowNames) {
300          s.Append(Content.RowNames.ElementAt(rowIndex));
301          s.Append('\t');
302        }
303
304        DataGridViewColumn column = dataGridView.Columns.GetFirstColumn(DataGridViewElementStates.Visible);
305        while (column != null) {
306          DataGridViewCell cell = dataGridView[column.Index, i];
307          if (cell.Selected) {
308            s.Append(Content.GetValue(rowIndex, column.Index));
309          }
310          s.Append('\t');
311          column = dataGridView.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None);
312        }
313        s.Remove(s.Length - 1, 1); //remove last tab
314        s.Append(Environment.NewLine);
315      }
316      Clipboard.SetText(s.ToString());
317    }
318
319    private void PasteValuesToDataGridView() {
320      string[,] values = SplitClipboardString(Clipboard.GetText());
321      int rowIndex = 0;
322      int columnIndex = 0;
323      if (dataGridView.CurrentCell != null) {
324        rowIndex = dataGridView.CurrentCell.RowIndex;
325        columnIndex = dataGridView.CurrentCell.ColumnIndex;
326      }
327
328      for (int row = 0; row < values.GetLength(1); row++) {
329        if (row + rowIndex >= Content.Rows)
330          Content.Rows = Content.Rows + 1;
331        for (int col = 0; col < values.GetLength(0); col++) {
332          if (col + columnIndex >= Content.Columns)
333            Content.Columns = Content.Columns + 1;
334          Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
335        }
336      }
337      ClearSorting();
338    }
339    private string[,] SplitClipboardString(string clipboardText) {
340      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
341      string[,] values = null;
342      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
343      string[] cells;
344      for (int i = 0; i < lines.Length; i++) {
345        cells = lines[i].Split('\t');
346        if (values == null)
347          values = new string[cells.Length, lines.Length];
348        for (int j = 0; j < cells.Length; j++)
349          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
350      }
351      return values;
352    }
353
354    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
355      if (Content != null) {
356        if (e.Button == MouseButtons.Left && Content.SortableView) {
357          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
358          SortOrder newSortOrder = SortOrder.Ascending;
359          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
360            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
361            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
362            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
363          }
364
365          if (!addToSortedIndizes)
366            sortedColumnIndizes.Clear();
367
368          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
369            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
370            if (newSortOrder != SortOrder.None)
371              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
372            else
373              sortedColumnIndizes.RemoveAt(sortedIndex);
374          } else
375            if (newSortOrder != SortOrder.None)
376              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
377          Sort();
378        } else if (e.Button == MouseButtons.Right) {
379          if (Content.ColumnNames.Count() != 0)
380            contextMenu.Show(MousePosition);
381        }
382      }
383    }
384
385    protected 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 ShowHideColumns_Click(object sender, EventArgs e) {
466      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
467    }
468  }
469}
Note: See TracBrowser for help on using the repository browser.