Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.0/HeuristicLab.Data.Views/3.3/StringConvertibleMatrixView.cs @ 3866

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

adapted view captions (ticket #893)

File size: 16.5 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    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      SetEnabledStateOfControls();
90    }
91    protected override void OnReadOnlyChanged() {
92      base.OnReadOnlyChanged();
93      SetEnabledStateOfControls();
94    }
95    private void SetEnabledStateOfControls() {
96      rowsTextBox.Enabled = Content != null;
97      columnsTextBox.Enabled = Content != null;
98      dataGridView.Enabled = Content != null;
99      rowsTextBox.ReadOnly = ReadOnly;
100      columnsTextBox.ReadOnly = ReadOnly;
101      dataGridView.ReadOnly = ReadOnly;
102    }
103
104    private void UpdateData() {
105      sortedColumnIndizes.Clear();
106      rowsTextBox.Text = Content.Rows.ToString();
107      rowsTextBox.Enabled = true;
108      columnsTextBox.Text = Content.Columns.ToString();
109      columnsTextBox.Enabled = true;
110      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
111      //DataGridViews with Rows but no columns are not allowed !
112      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
113        Content.Rows = dataGridView.RowCount;
114      else
115        dataGridView.RowCount = Content.Rows;
116      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
117        Content.Columns = dataGridView.ColumnCount;
118      else
119        dataGridView.ColumnCount = Content.Columns;
120
121      Sort();
122      UpdateRowHeaders();
123      UpdateColumnHeaders();
124      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
125      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
126      dataGridView.Enabled = true;
127    }
128
129    private void UpdateColumnHeaders() {
130      for (int i = 0; i < Content.Columns; i++) {
131        if (Content.ColumnNames.Count() != 0)
132          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
133        else
134          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
135      }
136      dataGridView.Invalidate();
137    }
138
139    private void UpdateRowHeaders() {
140      for (int i = 0; i < dataGridView.RowCount; i++) {
141        if (Content.RowNames.Count() != 0)
142          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
143        else
144          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
145      }
146      dataGridView.Invalidate();
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.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 (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    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
249      UpdateRowHeaders();
250    }
251    private void dataGridView_Resize(object sender, EventArgs e) {
252      UpdateRowHeaders();
253    }
254
255    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
256      if (!ReadOnly && e.Control && e.KeyCode == Keys.V) { //shortcut for values paste
257        string[,] values = SplitClipboardString(Clipboard.GetText());
258
259        int rowIndex = 0;
260        int columnIndex = 0;
261        if (dataGridView.CurrentCell != null) {
262          rowIndex = dataGridView.CurrentCell.RowIndex;
263          columnIndex = dataGridView.CurrentCell.ColumnIndex;
264        }
265
266        for (int row = 0; row < values.GetLength(1); row++) {
267          if (row + rowIndex >= Content.Rows)
268            Content.Rows = Content.Rows + 1;
269          for (int col = 0; col < values.GetLength(0); col++) {
270            if (col + columnIndex >= Content.Columns)
271              Content.Columns = Content.Columns + 1;
272            Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
273          }
274        }
275
276        ClearSorting();
277      }
278    }
279
280    private string[,] SplitClipboardString(string clipboardText) {
281      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
282      string[,] values = null;
283      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
284      string[] cells;
285      for (int i = 0; i < lines.Length; i++) {
286        cells = lines[i].Split('\t');
287        if (values == null)
288          values = new string[cells.Length, lines.Length];
289        for (int j = 0; j < cells.Length; j++)
290          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
291      }
292      return values;
293    }
294
295    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
296      if (Content != null) {
297        if (e.Button == MouseButtons.Left && Content.SortableView) {
298          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
299          SortOrder newSortOrder = SortOrder.Ascending;
300          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
301            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
302            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
303            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
304          }
305
306          if (!addToSortedIndizes)
307            sortedColumnIndizes.Clear();
308
309          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
310            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
311            if (newSortOrder != SortOrder.None)
312              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
313            else
314              sortedColumnIndizes.RemoveAt(sortedIndex);
315          } else
316            if (newSortOrder != SortOrder.None)
317              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
318          Sort();
319        } else if (e.Button == MouseButtons.Right) {
320          if (Content.ColumnNames.Count() != 0)
321            contextMenu.Show(MousePosition);
322        }
323      }
324    }
325
326    protected void ClearSorting() {
327      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
328      sortedColumnIndizes.Clear();
329      UpdateSortGlyph();
330    }
331
332    private void Sort() {
333      virtualRowIndizes = Sort(sortedColumnIndizes);
334      UpdateSortGlyph();
335      UpdateRowHeaders();
336      dataGridView.Invalidate();
337    }
338    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
339      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
340      if (sortedColumns.Count() != 0) {
341        rowComparer.SortedIndizes = sortedColumns;
342        rowComparer.Matrix = Content;
343        Array.Sort(newSortedIndex, rowComparer);
344      }
345      return newSortedIndex;
346    }
347    private void UpdateSortGlyph() {
348      foreach (DataGridViewColumn col in this.dataGridView.Columns)
349        col.HeaderCell.SortGlyphDirection = SortOrder.None;
350      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
351        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
352    }
353    #endregion
354
355    public class RowComparer : IComparer<int> {
356      public RowComparer() {
357      }
358
359      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
360      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
361        get { return this.sortedIndizes; }
362        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
363      }
364      private IStringConvertibleMatrix matrix;
365      public IStringConvertibleMatrix Matrix {
366        get { return this.matrix; }
367        set { this.matrix = value; }
368      }
369
370      public int Compare(int x, int y) {
371        int result = 0;
372        double double1, double2;
373        DateTime dateTime1, dateTime2;
374        TimeSpan timeSpan1, timeSpan2;
375        string string1, string2;
376
377        if (matrix == null)
378          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
379        if (sortedIndizes == null)
380          return 0;
381
382        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
383          string1 = matrix.GetValue(x, pair.Key);
384          string2 = matrix.GetValue(y, pair.Key);
385          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
386            result = double1.CompareTo(double2);
387          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
388            result = dateTime1.CompareTo(dateTime2);
389          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
390            result = timeSpan1.CompareTo(timeSpan2);
391          else {
392            if (string1 != null)
393              result = string1.CompareTo(string2);
394            else if (string2 != null)
395              result = string2.CompareTo(string1) * -1;
396          }
397          if (pair.Value == SortOrder.Descending)
398            result *= -1;
399          if (result != 0)
400            return result;
401        }
402        return result;
403      }
404    }
405
406    private void ShowHideColumns_Click(object sender, EventArgs e) {
407      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
408    }
409  }
410}
Note: See TracBrowser for help on using the repository browser.