Free cookie consent management tool by TermsFeed Policy Generator

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

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

Implemented ReadOnlyView property for items (#969).

File size: 12.1 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    public new IStringConvertibleMatrix Content {
37      get { return (IStringConvertibleMatrix)base.Content; }
38      set { base.Content = value; }
39    }
40
41    private int[] virtualRowIndizes;
42    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
43    RowComparer rowComparer;
44
45    public StringConvertibleMatrixView() {
46      InitializeComponent();
47      Caption = "StringConvertibleMatrix View";
48      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
49      errorProvider.SetIconPadding(rowsTextBox, 2);
50      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
51      errorProvider.SetIconPadding(columnsTextBox, 2);
52      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
53      rowComparer = new RowComparer();
54    }
55    public StringConvertibleMatrixView(IStringConvertibleMatrix content)
56      : this() {
57      Content = content;
58    }
59
60    protected override void DeregisterContentEvents() {
61      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
62      Content.Reset -= new EventHandler(Content_Reset);
63      base.DeregisterContentEvents();
64    }
65
66
67    protected override void RegisterContentEvents() {
68      base.RegisterContentEvents();
69      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
70      Content.Reset += new EventHandler(Content_Reset);
71    }
72
73    protected override void OnContentChanged() {
74      base.OnContentChanged();
75      sortedColumnIndizes.Clear();
76      virtualRowIndizes = new int[0];
77      if (Content == null) {
78        Caption = "StringConvertibleMatrix View";
79        rowsTextBox.Text = "";
80        rowsTextBox.Enabled = false;
81        columnsTextBox.Text = "";
82        columnsTextBox.Enabled = false;
83        dataGridView.Rows.Clear();
84        dataGridView.Columns.Clear();
85        dataGridView.Enabled = false;
86      } else {
87        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
88        UpdateData();
89      }
90    }
91
92    private void UpdateData() {
93      rowsTextBox.Text = Content.Rows.ToString();
94      rowsTextBox.Enabled = true;
95      columnsTextBox.Text = Content.Columns.ToString();
96      columnsTextBox.Enabled = true;
97      dataGridView.RowCount = 0;
98      dataGridView.ColumnCount = 0;
99      if ((Content.Rows > 0) && (Content.Columns > 0)) {
100        virtualRowIndizes = Enumerable.Range(0, Content.Rows - 1).ToArray();
101        dataGridView.RowCount = Content.Rows;
102        dataGridView.ColumnCount = Content.Columns;
103        UpdateRowHeaders();
104        UpdateColumnHeaders();
105      }
106      dataGridView.ReadOnly = Content.ReadOnlyView;
107      dataGridView.Enabled = true;
108    }
109
110    private void UpdateColumnHeaders() {
111      for (int i = 0; i < Content.Columns; i++) {
112        if (Content.ColumnNames.Count() != 0)
113          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
114        else
115          dataGridView.Columns[i].HeaderText = "Column " + i;
116      }
117      dataGridView.Invalidate();
118    }
119
120    private void UpdateRowHeaders() {
121      for (int i = dataGridView.FirstDisplayedScrollingRowIndex; i < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(true); i++) {
122        if (Content.RowNames.Count() != 0)
123          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(i);
124        else
125          dataGridView.Rows[i].HeaderCell.Value = i.ToString();
126      }
127      dataGridView.Invalidate();
128    }
129
130    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
131      if (InvokeRequired)
132        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
133      else {
134        dataGridView.InvalidateCell(e.Value, e.Value2);
135      }
136    }
137    private void Content_Reset(object sender, EventArgs e) {
138      if (InvokeRequired)
139        Invoke(new EventHandler(Content_Reset), sender, e);
140      else
141        UpdateData();
142    }
143
144    #region TextBox Events
145    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
146      int i = 0;
147      if (!int.TryParse(rowsTextBox.Text, out i) || (i < 0)) {
148        e.Cancel = true;
149        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid Values: Positive Integers Larger or Equal to 0)");
150        rowsTextBox.SelectAll();
151      }
152    }
153    private void rowsTextBox_Validated(object sender, EventArgs e) {
154      Content.Rows = int.Parse(rowsTextBox.Text);
155      errorProvider.SetError(rowsTextBox, string.Empty);
156    }
157    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
158      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
159        rowsLabel.Focus();  // set focus on label to validate data
160      if (e.KeyCode == Keys.Escape) {
161        rowsTextBox.Text = Content.Rows.ToString();
162        rowsLabel.Focus();  // set focus on label to validate data
163      }
164    }
165    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
166      int i = 0;
167      if (!int.TryParse(columnsTextBox.Text, out i) || (i < 0)) {
168        e.Cancel = true;
169        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid Values: Positive Integers Larger or Equal to 0)");
170        columnsTextBox.SelectAll();
171      }
172    }
173    private void columnsTextBox_Validated(object sender, EventArgs e) {
174      Content.Columns = int.Parse(columnsTextBox.Text);
175      errorProvider.SetError(columnsTextBox, string.Empty);
176    }
177    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
178      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
179        columnsLabel.Focus();  // set focus on label to validate data
180      if (e.KeyCode == Keys.Escape) {
181        columnsTextBox.Text = Content.Columns.ToString();
182        columnsLabel.Focus();  // set focus on label to validate data
183      }
184    }
185    #endregion
186
187    #region DataGridView Events
188    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
189      string errorMessage;
190      if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
191        e.Cancel = true;
192        dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
193      }
194    }
195    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
196      string value = e.Value.ToString();
197      int rowIndex = virtualRowIndizes[e.RowIndex];
198      e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
199      if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
200    }
201    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
202      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
203    }
204    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
205      if (e.RowIndex < virtualRowIndizes.Length) {
206        int rowIndex = virtualRowIndizes[e.RowIndex];
207        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
208      }
209    }
210
211    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
212      UpdateRowHeaders();
213    }
214
215    private void dataGridView_Resize(object sender, EventArgs e) {
216      UpdateRowHeaders();
217    }
218
219    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
220      //if (Content != null && Content.SortableView) {
221      if (e.Button == MouseButtons.Left) {
222        bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
223        SortOrder newSortOrder = SortOrder.Ascending;
224        if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
225          SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
226          int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
227          newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
228        }
229
230        if (!addToSortedIndizes)
231          sortedColumnIndizes.Clear();
232
233        if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
234          int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
235          if (newSortOrder != SortOrder.None)
236            sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
237          else
238            sortedColumnIndizes.RemoveAt(sortedIndex);
239        } else
240          if (newSortOrder != SortOrder.None)
241            sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
242        Sort();
243      } else if (e.Button == MouseButtons.Right) {
244        if (Content.ColumnNames.Count() != 0)
245          contextMenu.Show(MousePosition);
246      }
247
248      //}
249    }
250
251    private void Sort() {
252      int[] newSortedIndex = Enumerable.Range(0, Content.Rows - 1).ToArray();
253      if (sortedColumnIndizes.Count != 0) {
254        rowComparer.sortedIndizes = sortedColumnIndizes;
255        rowComparer.matrix = Content;
256        Array.Sort(newSortedIndex, rowComparer);
257      }
258      virtualRowIndizes = newSortedIndex;
259      dataGridView.Invalidate();
260      foreach (DataGridViewColumn col in this.dataGridView.Columns)
261        col.HeaderCell.SortGlyphDirection = SortOrder.None;
262      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
263        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
264    }
265    #endregion
266
267    private class RowComparer : IComparer<int> {
268      public List<KeyValuePair<int, SortOrder>> sortedIndizes;
269      public IStringConvertibleMatrix matrix;
270      public RowComparer() {
271      }
272
273      public int Compare(int x, int y) {
274        int result = 0;
275        double double1, double2;
276        DateTime dateTime1, dateTime2;
277        string string1, string2;
278
279        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes) {
280          string1 = matrix.GetValue(x, pair.Key);
281          string2 = matrix.GetValue(y, pair.Key);
282          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
283            result = double1.CompareTo(double2);
284          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
285            result = dateTime1.CompareTo(dateTime2);
286          else {
287            if (string1 != null)
288              result = string1.CompareTo(string2);
289            else if (string2 != null)
290              result = string2.CompareTo(string1) * -1;
291          }
292          if (pair.Value == SortOrder.Descending)
293            result *= -1;
294          if (result != 0)
295            return result;
296        }
297        return result;
298      }
299    }
300
301    private void ShowHideColumns_Click(object sender, EventArgs e) {
302      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
303    }
304  }
305}
Note: See TracBrowser for help on using the repository browser.