Free cookie consent management tool by TermsFeed Policy Generator

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

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

added paste support for StringConvertibleMatrixView (ticket #968)

File size: 16.6 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      Caption = "StringConvertibleMatrix View";
56      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
57      errorProvider.SetIconPadding(rowsTextBox, 2);
58      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
59      errorProvider.SetIconPadding(columnsTextBox, 2);
60      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
61      rowComparer = new RowComparer();
62    }
63
64    protected override void DeregisterContentEvents() {
65      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
66      Content.Reset -= new EventHandler(Content_Reset);
67      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
68      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
69      base.DeregisterContentEvents();
70    }
71    protected override void RegisterContentEvents() {
72      base.RegisterContentEvents();
73      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
74      Content.Reset += new EventHandler(Content_Reset);
75      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
76      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
77    }
78
79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
82        Caption = "StringConvertibleMatrix View";
83        rowsTextBox.Text = "";
84        columnsTextBox.Text = "";
85        dataGridView.Rows.Clear();
86        dataGridView.Columns.Clear();
87        virtualRowIndizes = new int[0];
88      } else {
89        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
90        UpdateData();
91      }
92      SetEnabledStateOfControls();
93    }
94    protected override void OnReadOnlyChanged() {
95      base.OnReadOnlyChanged();
96      SetEnabledStateOfControls();
97    }
98    private void SetEnabledStateOfControls() {
99      rowsTextBox.Enabled = Content != null;
100      columnsTextBox.Enabled = Content != null;
101      dataGridView.Enabled = Content != null;
102      rowsTextBox.ReadOnly = ReadOnly;
103      columnsTextBox.ReadOnly = ReadOnly;
104      dataGridView.ReadOnly = ReadOnly;
105    }
106
107    private void UpdateData() {
108      sortedColumnIndizes.Clear();
109      rowsTextBox.Text = Content.Rows.ToString();
110      rowsTextBox.Enabled = true;
111      columnsTextBox.Text = Content.Columns.ToString();
112      columnsTextBox.Enabled = true;
113      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
114      //DataGridViews with Rows but no columns are not allowed !
115      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
116        Content.Rows = dataGridView.RowCount;
117      else
118        dataGridView.RowCount = Content.Rows;
119      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
120        Content.Columns = dataGridView.ColumnCount;
121      else
122        dataGridView.ColumnCount = Content.Columns;
123
124      Sort();
125      UpdateRowHeaders();
126      UpdateColumnHeaders();
127      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
128      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
129      dataGridView.Enabled = true;
130    }
131
132    private void UpdateColumnHeaders() {
133      for (int i = 0; i < Content.Columns; i++) {
134        if (Content.ColumnNames.Count() != 0)
135          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
136        else
137          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
138      }
139      dataGridView.Invalidate();
140    }
141
142    private void UpdateRowHeaders() {
143      for (int i = 0; i < dataGridView.RowCount; i++) {
144        if (Content.RowNames.Count() != 0)
145          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
146        else
147          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
148      }
149      dataGridView.Invalidate();
150    }
151
152    private void Content_RowNamesChanged(object sender, EventArgs e) {
153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
155      else
156        UpdateRowHeaders();
157    }
158    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
159      if (InvokeRequired)
160        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
161      else
162        UpdateColumnHeaders();
163    }
164    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
165      if (InvokeRequired)
166        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
167      else
168        dataGridView.InvalidateCell(e.Value2, e.Value);
169    }
170    private void Content_Reset(object sender, EventArgs e) {
171      if (InvokeRequired)
172        Invoke(new EventHandler(Content_Reset), sender, e);
173      else
174        UpdateData();
175    }
176
177    #region TextBox Events
178    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
179      int i = 0;
180      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
181        e.Cancel = true;
182        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
183        rowsTextBox.SelectAll();
184      }
185    }
186    private void rowsTextBox_Validated(object sender, EventArgs e) {
187      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
188      errorProvider.SetError(rowsTextBox, string.Empty);
189    }
190    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
191      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
192        rowsLabel.Focus();  // set focus on label to validate data
193      if (e.KeyCode == Keys.Escape) {
194        rowsTextBox.Text = Content.Rows.ToString();
195        rowsLabel.Focus();  // set focus on label to validate data
196      }
197    }
198    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
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.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 (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    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
248      UpdateRowHeaders();
249    }
250    private void dataGridView_Resize(object sender, EventArgs e) {
251      UpdateRowHeaders();
252    }
253
254    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
255      if (!ReadOnly && e.Control && e.KeyCode == Keys.V) { //shortcut for values paste
256        string[,] values = SplitClipboardString(Clipboard.GetText());
257
258        int rowIndex = 0;
259        int columnIndex = 0;
260        if (dataGridView.CurrentCell != null) {
261          rowIndex = dataGridView.CurrentCell.RowIndex;
262          columnIndex = dataGridView.CurrentCell.ColumnIndex;
263        }
264
265        for (int row = 0; row < values.GetLength(1); row++) {
266          if (row + rowIndex >= Content.Rows)
267            Content.Rows = Content.Rows + 1;
268          for (int col = 0; col < values.GetLength(0); col++) {
269            if (col + columnIndex >= Content.Columns)
270              Content.Columns = Content.Columns + 1;
271            Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
272          }
273        }
274
275        ClearSorting();
276      }
277    }
278
279    private string[,] SplitClipboardString(string clipboardText) {
280      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
281      string[,] values = null;
282      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
283      string[] cells;
284      for (int i = 0; i < lines.Length; i++) {
285        cells = lines[i].Split('\t');
286        if (values == null)
287          values = new string[cells.Length, lines.Length];
288        for (int j = 0; j < cells.Length; j++)
289          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
290      }
291      return values;
292    }
293
294    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
295      if (Content != null) {
296        if (e.Button == MouseButtons.Left && Content.SortableView) {
297          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
298          SortOrder newSortOrder = SortOrder.Ascending;
299          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
300            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
301            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
302            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
303          }
304
305          if (!addToSortedIndizes)
306            sortedColumnIndizes.Clear();
307
308          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
309            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
310            if (newSortOrder != SortOrder.None)
311              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
312            else
313              sortedColumnIndizes.RemoveAt(sortedIndex);
314          } else
315            if (newSortOrder != SortOrder.None)
316              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
317          Sort();
318        } else if (e.Button == MouseButtons.Right) {
319          if (Content.ColumnNames.Count() != 0)
320            contextMenu.Show(MousePosition);
321        }
322      }
323    }
324
325    protected void ClearSorting() {
326      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
327      sortedColumnIndizes.Clear();
328      UpdateSortGlyph();
329    }
330
331    private void Sort() {
332      virtualRowIndizes = Sort(sortedColumnIndizes);
333      UpdateSortGlyph();
334      UpdateRowHeaders();
335      dataGridView.Invalidate();
336    }
337    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
338      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
339      if (sortedColumns.Count() != 0) {
340        rowComparer.SortedIndizes = sortedColumns;
341        rowComparer.Matrix = Content;
342        Array.Sort(newSortedIndex, rowComparer);
343      }
344      return newSortedIndex;
345    }
346    private void UpdateSortGlyph() {
347      foreach (DataGridViewColumn col in this.dataGridView.Columns)
348        col.HeaderCell.SortGlyphDirection = SortOrder.None;
349      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
350        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
351    }
352    #endregion
353
354    public class RowComparer : IComparer<int> {
355      public RowComparer() {
356      }
357
358      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
359      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
360        get { return this.sortedIndizes; }
361        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
362      }
363      private IStringConvertibleMatrix matrix;
364      public IStringConvertibleMatrix Matrix {
365        get { return this.matrix; }
366        set { this.matrix = value; }
367      }
368
369      public int Compare(int x, int y) {
370        int result = 0;
371        double double1, double2;
372        DateTime dateTime1, dateTime2;
373        TimeSpan timeSpan1, timeSpan2;
374        string string1, string2;
375
376        if (matrix == null)
377          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
378        if (sortedIndizes == null)
379          return 0;
380
381        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
382          string1 = matrix.GetValue(x, pair.Key);
383          string2 = matrix.GetValue(y, pair.Key);
384          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
385            result = double1.CompareTo(double2);
386          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
387            result = dateTime1.CompareTo(dateTime2);
388          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
389            result = timeSpan1.CompareTo(timeSpan2);
390          else {
391            if (string1 != null)
392              result = string1.CompareTo(string2);
393            else if (string2 != null)
394              result = string2.CompareTo(string1) * -1;
395          }
396          if (pair.Value == SortOrder.Descending)
397            result *= -1;
398          if (result != 0)
399            return result;
400        }
401        return result;
402      }
403    }
404
405    private void ShowHideColumns_Click(object sender, EventArgs e) {
406      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
407    }
408  }
409}
Note: See TracBrowser for help on using the repository browser.