Free cookie consent management tool by TermsFeed Policy Generator

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

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

adapted view captions (ticket #893)

File size: 16.5 KB
RevLine 
[2669]1#region License Information
2/* HeuristicLab
[2790]3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2669]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;
[3314]24using System.Collections.Generic;
[2669]25using System.Drawing;
[3312]26using System.Linq;
[2669]27using System.Windows.Forms;
28using HeuristicLab.Common;
29using HeuristicLab.MainForm;
[2713]30using HeuristicLab.MainForm.WindowsForms;
[2669]31
32namespace HeuristicLab.Data.Views {
[3048]33  [View("StringConvertibleMatrix View")]
34  [Content(typeof(IStringConvertibleMatrix), true)]
[3228]35  public partial class StringConvertibleMatrixView : AsynchronousContentView {
[3448]36    protected int[] virtualRowIndizes;
[3430]37    private List<KeyValuePair<int, SortOrder>> sortedColumnIndizes;
38    private RowComparer rowComparer;
39
[3048]40    public new IStringConvertibleMatrix Content {
41      get { return (IStringConvertibleMatrix)base.Content; }
[2713]42      set { base.Content = value; }
[2669]43    }
44
[3430]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    }
[3314]52
[3048]53    public StringConvertibleMatrixView() {
[2669]54      InitializeComponent();
[2677]55      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
56      errorProvider.SetIconPadding(rowsTextBox, 2);
57      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
58      errorProvider.SetIconPadding(columnsTextBox, 2);
[3314]59      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
60      rowComparer = new RowComparer();
[2669]61    }
62
[2713]63    protected override void DeregisterContentEvents() {
64      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
65      Content.Reset -= new EventHandler(Content_Reset);
[3320]66      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
67      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
[2713]68      base.DeregisterContentEvents();
[2669]69    }
[2713]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);
[3320]74      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
75      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
[2669]76    }
77
[2713]78    protected override void OnContentChanged() {
79      base.OnContentChanged();
80      if (Content == null) {
[2677]81        rowsTextBox.Text = "";
82        columnsTextBox.Text = "";
[2669]83        dataGridView.Rows.Clear();
[2677]84        dataGridView.Columns.Clear();
[3324]85        virtualRowIndizes = new int[0];
[3764]86      } else
[2713]87        UpdateData();
[3764]88
[3362]89      SetEnabledStateOfControls();
[2669]90    }
[3350]91    protected override void OnReadOnlyChanged() {
92      base.OnReadOnlyChanged();
[3362]93      SetEnabledStateOfControls();
[3350]94    }
[3362]95    private void SetEnabledStateOfControls() {
[3454]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;
[3350]102    }
[2669]103
[2713]104    private void UpdateData() {
[3328]105      sortedColumnIndizes.Clear();
[2713]106      rowsTextBox.Text = Content.Rows.ToString();
[2973]107      rowsTextBox.Enabled = true;
[2713]108      columnsTextBox.Text = Content.Columns.ToString();
[2973]109      columnsTextBox.Enabled = true;
[3324]110      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
[3335]111      //DataGridViews with Rows but no columns are not allowed !
[3431]112      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
[3335]113        Content.Rows = dataGridView.RowCount;
114      else
115        dataGridView.RowCount = Content.Rows;
[3431]116      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
[3335]117        Content.Columns = dataGridView.ColumnCount;
118      else
119        dataGridView.ColumnCount = Content.Columns;
[3346]120
[3643]121      Sort();
[3328]122      UpdateRowHeaders();
123      UpdateColumnHeaders();
[3346]124      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
125      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
[2669]126      dataGridView.Enabled = true;
127    }
128
[3312]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
[3346]134          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
[3312]135      }
136      dataGridView.Invalidate();
137    }
138
139    private void UpdateRowHeaders() {
[3546]140      for (int i = 0; i < dataGridView.RowCount; i++) {
[3312]141        if (Content.RowNames.Count() != 0)
[3546]142          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
[3314]143        else
[3346]144          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
[3312]145      }
146      dataGridView.Invalidate();
147    }
148
[3320]149    private void Content_RowNamesChanged(object sender, EventArgs e) {
[3328]150      if (InvokeRequired)
151        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
152      else
153        UpdateRowHeaders();
[3320]154    }
155    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
[3328]156      if (InvokeRequired)
157        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
158      else
159        UpdateColumnHeaders();
[3320]160    }
[2713]161    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
[2669]162      if (InvokeRequired)
[2713]163        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
[3328]164      else
[3335]165        dataGridView.InvalidateCell(e.Value2, e.Value);
[2669]166    }
[2713]167    private void Content_Reset(object sender, EventArgs e) {
[2669]168      if (InvokeRequired)
[2713]169        Invoke(new EventHandler(Content_Reset), sender, e);
[2669]170      else
[2713]171        UpdateData();
[2669]172    }
173
[2677]174    #region TextBox Events
175    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
[3714]176      if (ReadOnly || Locked)
177        return;
[2669]178      int i = 0;
[3335]179      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
[2676]180        e.Cancel = true;
[3335]181        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
[2677]182        rowsTextBox.SelectAll();
[2669]183      }
184    }
[2677]185    private void rowsTextBox_Validated(object sender, EventArgs e) {
[3430]186      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
[2677]187      errorProvider.SetError(rowsTextBox, string.Empty);
[2669]188    }
[2677]189    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
[2669]190      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
[2677]191        rowsLabel.Focus();  // set focus on label to validate data
[2676]192      if (e.KeyCode == Keys.Escape) {
[2973]193        rowsTextBox.Text = Content.Rows.ToString();
[2677]194        rowsLabel.Focus();  // set focus on label to validate data
[2676]195      }
[2669]196    }
[2677]197    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
[3714]198      if (ReadOnly || Locked)
199        return;
[2677]200      int i = 0;
[3335]201      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
[2677]202        e.Cancel = true;
[3335]203        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
[2677]204        columnsTextBox.SelectAll();
205      }
206    }
207    private void columnsTextBox_Validated(object sender, EventArgs e) {
[3430]208      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
[2677]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) {
[2713]215        columnsTextBox.Text = Content.Columns.ToString();
[2677]216        columnsLabel.Focus();  // set focus on label to validate data
217      }
218    }
219    #endregion
220
221    #region DataGridView Events
[2669]222    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
[3328]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        }
[2676]229      }
[2669]230    }
[2676]231    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
[3328]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      }
[2669]238    }
[2676]239    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
240      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
241    }
[3312]242    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
[3337]243      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
244        int rowIndex = virtualRowIndizes[e.RowIndex];
[3335]245        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
[3337]246      }
[3312]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    }
[3314]254
[3643]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
[3314]295    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
[3320]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          }
[3314]305
[3320]306          if (!addToSortedIndizes)
307            sortedColumnIndizes.Clear();
[3314]308
[3320]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        }
[3314]323      }
324    }
325
[3643]326    protected void ClearSorting() {
327      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
328      sortedColumnIndizes.Clear();
329      UpdateSortGlyph();
330    }
331
[3314]332    private void Sort() {
[3444]333      virtualRowIndizes = Sort(sortedColumnIndizes);
334      UpdateSortGlyph();
[3546]335      UpdateRowHeaders();
[3444]336      dataGridView.Invalidate();
337    }
338    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
[3328]339      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
[3444]340      if (sortedColumns.Count() != 0) {
341        rowComparer.SortedIndizes = sortedColumns;
[3346]342        rowComparer.Matrix = Content;
[3314]343        Array.Sort(newSortedIndex, rowComparer);
344      }
[3444]345      return newSortedIndex;
[3328]346    }
347    private void UpdateSortGlyph() {
[3314]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    }
[2677]353    #endregion
[3312]354
[3346]355    public class RowComparer : IComparer<int> {
[3314]356      public RowComparer() {
357      }
[3312]358
[3346]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
[3314]370      public int Compare(int x, int y) {
371        int result = 0;
372        double double1, double2;
373        DateTime dateTime1, dateTime2;
[3444]374        TimeSpan timeSpan1, timeSpan2;
[3314]375        string string1, string2;
376
[3346]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)) {
[3350]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);
[3444]389          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
390            result = timeSpan1.CompareTo(timeSpan2);
[3350]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;
[3314]401        }
402        return result;
403      }
404    }
[3316]405
406    private void ShowHideColumns_Click(object sender, EventArgs e) {
407      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
408    }
[2669]409  }
410}
Note: See TracBrowser for help on using the repository browser.