Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 16.9 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.Windows.Forms;
27using HeuristicLab.Common;
28using HeuristicLab.MainForm;
29using HeuristicLab.MainForm.WindowsForms;
30
31namespace HeuristicLab.Data.Views {
32  [View("StringConvertibleMatrix View")]
33  [Content(typeof(IStringConvertibleMatrix), true)]
34  public partial class StringConvertibleMatrixView : AsynchronousContentView {
35    protected int[] virtualRowIndizes;
36    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
37    private RowComparer rowComparer;
38
39    public new IStringConvertibleMatrix Content {
40      get { return (IStringConvertibleMatrix)base.Content; }
41      set { base.Content = value; }
42    }
43
44    public override bool ReadOnly {
45      get {
46        if ((Content != null) && Content.ReadOnly) return true;
47        return base.ReadOnly;
48      }
49      set { base.ReadOnly = value; }
50    }
51
52    public StringConvertibleMatrixView() {
53      InitializeComponent();
54      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
55      errorProvider.SetIconPadding(rowsTextBox, 2);
56      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
57      errorProvider.SetIconPadding(columnsTextBox, 2);
58      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
59      rowComparer = new RowComparer();
60    }
61
62    protected override void DeregisterContentEvents() {
63      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
64      Content.Reset -= new EventHandler(Content_Reset);
65      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
66      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
67      base.DeregisterContentEvents();
68    }
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
72      Content.Reset += new EventHandler(Content_Reset);
73      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
74      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
75    }
76
77    protected override void OnContentChanged() {
78      base.OnContentChanged();
79      if (Content == null) {
80        rowsTextBox.Text = "";
81        columnsTextBox.Text = "";
82        dataGridView.Rows.Clear();
83        dataGridView.Columns.Clear();
84        virtualRowIndizes = new int[0];
85      } else
86        UpdateData();
87    }
88
89    protected override void SetEnabledStateOfControls() {
90      base.SetEnabledStateOfControls();
91      rowsTextBox.Enabled = Content != null;
92      columnsTextBox.Enabled = Content != null;
93      dataGridView.Enabled = Content != null;
94      rowsTextBox.ReadOnly = ReadOnly;
95      columnsTextBox.ReadOnly = ReadOnly;
96      dataGridView.ReadOnly = ReadOnly;
97    }
98
99    private void UpdateData() {
100      ClearSorting();
101      rowsTextBox.Text = Content.Rows.ToString();
102      rowsTextBox.Enabled = true;
103      columnsTextBox.Text = Content.Columns.ToString();
104      columnsTextBox.Enabled = true;
105      //DataGridViews with Rows but no columns are not allowed !
106      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
107        Content.Rows = dataGridView.RowCount;
108      else
109        dataGridView.RowCount = Content.Rows;
110      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
111        Content.Columns = dataGridView.ColumnCount;
112      else
113        dataGridView.ColumnCount = Content.Columns;
114
115      UpdateRowHeaders();
116      UpdateColumnHeaders();
117      dataGridView.Enabled = true;
118    }
119
120    private void UpdateColumnHeaders() {
121      int firstDisplayedColumnIndex = this.dataGridView.FirstDisplayedScrollingColumnIndex;
122      if (firstDisplayedColumnIndex == -1)
123        firstDisplayedColumnIndex = 0;
124      int lastDisplayedColumnIndex = firstDisplayedColumnIndex + dataGridView.DisplayedColumnCount(true);
125      for (int i = firstDisplayedColumnIndex; i < lastDisplayedColumnIndex; 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      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
132    }
133
134    private void UpdateRowHeaders() {
135      int firstDisplayedRowIndex = dataGridView.FirstDisplayedScrollingRowIndex;
136      if (firstDisplayedRowIndex == -1)
137        firstDisplayedRowIndex = 0;
138      int lastDisplaydRowIndex = firstDisplayedRowIndex + dataGridView.DisplayedRowCount(true);
139      for (int i = firstDisplayedRowIndex; i < lastDisplaydRowIndex; i++) {
140        if (Content.RowNames.Count() != 0)
141          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
142        else
143          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
144      }
145      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
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    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
248      UpdateRowHeaders();
249      UpdateColumnHeaders();
250    }
251    private void dataGridView_Resize(object sender, EventArgs e) {
252      UpdateRowHeaders();
253      UpdateColumnHeaders();
254    }
255
256    private void dataGridView_KeyDown(object sender, KeyEventArgs e) {
257      if (!ReadOnly && e.Control && e.KeyCode == Keys.V) { //shortcut for values paste
258        string[,] values = SplitClipboardString(Clipboard.GetText());
259
260        int rowIndex = 0;
261        int columnIndex = 0;
262        if (dataGridView.CurrentCell != null) {
263          rowIndex = dataGridView.CurrentCell.RowIndex;
264          columnIndex = dataGridView.CurrentCell.ColumnIndex;
265        }
266
267        for (int row = 0; row < values.GetLength(1); row++) {
268          if (row + rowIndex >= Content.Rows)
269            Content.Rows = Content.Rows + 1;
270          for (int col = 0; col < values.GetLength(0); col++) {
271            if (col + columnIndex >= Content.Columns)
272              Content.Columns = Content.Columns + 1;
273            Content.SetValue(values[col, row], row + rowIndex, col + columnIndex);
274          }
275        }
276
277        ClearSorting();
278      }
279    }
280
281    private string[,] SplitClipboardString(string clipboardText) {
282      clipboardText = clipboardText.Remove(clipboardText.Length - Environment.NewLine.Length);  //remove last newline constant
283      string[,] values = null;
284      string[] lines = clipboardText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
285      string[] cells;
286      for (int i = 0; i < lines.Length; i++) {
287        cells = lines[i].Split('\t');
288        if (values == null)
289          values = new string[cells.Length, lines.Length];
290        for (int j = 0; j < cells.Length; j++)
291          values[j, i] = string.IsNullOrEmpty(cells[j]) ? string.Empty : cells[j];
292      }
293      return values;
294    }
295
296    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
297      if (Content != null) {
298        if (e.Button == MouseButtons.Left && Content.SortableView) {
299          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
300          SortOrder newSortOrder = SortOrder.Ascending;
301          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
302            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
303            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
304            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
305          }
306
307          if (!addToSortedIndizes)
308            sortedColumnIndizes.Clear();
309
310          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
311            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
312            if (newSortOrder != SortOrder.None)
313              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
314            else
315              sortedColumnIndizes.RemoveAt(sortedIndex);
316          } else
317            if (newSortOrder != SortOrder.None)
318              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
319          Sort();
320        } else if (e.Button == MouseButtons.Right) {
321          if (Content.ColumnNames.Count() != 0)
322            contextMenu.Show(MousePosition);
323        }
324      }
325    }
326
327    protected void ClearSorting() {
328      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
329      sortedColumnIndizes.Clear();
330      UpdateSortGlyph();
331    }
332
333    private void Sort() {
334      virtualRowIndizes = Sort(sortedColumnIndizes);
335      UpdateSortGlyph();
336      UpdateRowHeaders();
337      dataGridView.Invalidate();
338    }
339    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
340      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
341      if (sortedColumns.Count() != 0) {
342        rowComparer.SortedIndizes = sortedColumns;
343        rowComparer.Matrix = Content;
344        Array.Sort(newSortedIndex, rowComparer);
345      }
346      return newSortedIndex;
347    }
348    private void UpdateSortGlyph() {
349      foreach (DataGridViewColumn col in this.dataGridView.Columns)
350        col.HeaderCell.SortGlyphDirection = SortOrder.None;
351      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
352        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
353    }
354    #endregion
355
356    public class RowComparer : IComparer<int> {
357      public RowComparer() {
358      }
359
360      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
361      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
362        get { return this.sortedIndizes; }
363        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
364      }
365      private IStringConvertibleMatrix matrix;
366      public IStringConvertibleMatrix Matrix {
367        get { return this.matrix; }
368        set { this.matrix = value; }
369      }
370
371      public int Compare(int x, int y) {
372        int result = 0;
373        double double1, double2;
374        DateTime dateTime1, dateTime2;
375        TimeSpan timeSpan1, timeSpan2;
376        string string1, string2;
377
378        if (matrix == null)
379          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
380        if (sortedIndizes == null)
381          return 0;
382
383        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
384          string1 = matrix.GetValue(x, pair.Key);
385          string2 = matrix.GetValue(y, pair.Key);
386          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
387            result = double1.CompareTo(double2);
388          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
389            result = dateTime1.CompareTo(dateTime2);
390          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
391            result = timeSpan1.CompareTo(timeSpan2);
392          else {
393            if (string1 != null)
394              result = string1.CompareTo(string2);
395            else if (string2 != null)
396              result = string2.CompareTo(string1) * -1;
397          }
398          if (pair.Value == SortOrder.Descending)
399            result *= -1;
400          if (result != 0)
401            return result;
402        }
403        return result;
404      }
405    }
406
407    private void ShowHideColumns_Click(object sender, EventArgs e) {
408      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
409    }
410  }
411}
Note: See TracBrowser for help on using the repository browser.