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
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();
[3048]55      Caption = "StringConvertibleMatrix View";
[2677]56      errorProvider.SetIconAlignment(rowsTextBox, ErrorIconAlignment.MiddleLeft);
57      errorProvider.SetIconPadding(rowsTextBox, 2);
58      errorProvider.SetIconAlignment(columnsTextBox, ErrorIconAlignment.MiddleLeft);
59      errorProvider.SetIconPadding(columnsTextBox, 2);
[3314]60      sortedColumnIndizes = new List<KeyValuePair<int, SortOrder>>();
61      rowComparer = new RowComparer();
[2669]62    }
63
[2713]64    protected override void DeregisterContentEvents() {
65      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
66      Content.Reset -= new EventHandler(Content_Reset);
[3320]67      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
68      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
[2713]69      base.DeregisterContentEvents();
[2669]70    }
[2713]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);
[3320]75      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
76      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
[2669]77    }
78
[2713]79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      if (Content == null) {
[3048]82        Caption = "StringConvertibleMatrix View";
[2677]83        rowsTextBox.Text = "";
84        columnsTextBox.Text = "";
[2669]85        dataGridView.Rows.Clear();
[2677]86        dataGridView.Columns.Clear();
[3324]87        virtualRowIndizes = new int[0];
[2669]88      } else {
[3048]89        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
[2713]90        UpdateData();
[2669]91      }
[3362]92      SetEnabledStateOfControls();
[2669]93    }
[3350]94    protected override void OnReadOnlyChanged() {
95      base.OnReadOnlyChanged();
[3362]96      SetEnabledStateOfControls();
[3350]97    }
[3362]98    private void SetEnabledStateOfControls() {
[3454]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;
[3350]105    }
[2669]106
[2713]107    private void UpdateData() {
[3328]108      sortedColumnIndizes.Clear();
[2713]109      rowsTextBox.Text = Content.Rows.ToString();
[2973]110      rowsTextBox.Enabled = true;
[2713]111      columnsTextBox.Text = Content.Columns.ToString();
[2973]112      columnsTextBox.Enabled = true;
[3324]113      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
[3335]114      //DataGridViews with Rows but no columns are not allowed !
[3431]115      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
[3335]116        Content.Rows = dataGridView.RowCount;
117      else
118        dataGridView.RowCount = Content.Rows;
[3431]119      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
[3335]120        Content.Columns = dataGridView.ColumnCount;
121      else
122        dataGridView.ColumnCount = Content.Columns;
[3346]123
[3643]124      Sort();
[3328]125      UpdateRowHeaders();
126      UpdateColumnHeaders();
[3346]127      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
128      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
[2669]129      dataGridView.Enabled = true;
130    }
131
[3312]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
[3346]137          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
[3312]138      }
139      dataGridView.Invalidate();
140    }
141
142    private void UpdateRowHeaders() {
[3546]143      for (int i = 0; i < dataGridView.RowCount; i++) {
[3312]144        if (Content.RowNames.Count() != 0)
[3546]145          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(virtualRowIndizes[i]);
[3314]146        else
[3346]147          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
[3312]148      }
149      dataGridView.Invalidate();
150    }
151
[3320]152    private void Content_RowNamesChanged(object sender, EventArgs e) {
[3328]153      if (InvokeRequired)
154        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
155      else
156        UpdateRowHeaders();
[3320]157    }
158    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
[3328]159      if (InvokeRequired)
160        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
161      else
162        UpdateColumnHeaders();
[3320]163    }
[2713]164    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
[2669]165      if (InvokeRequired)
[2713]166        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
[3328]167      else
[3335]168        dataGridView.InvalidateCell(e.Value2, e.Value);
[2669]169    }
[2713]170    private void Content_Reset(object sender, EventArgs e) {
[2669]171      if (InvokeRequired)
[2713]172        Invoke(new EventHandler(Content_Reset), sender, e);
[2669]173      else
[2713]174        UpdateData();
[2669]175    }
176
[2677]177    #region TextBox Events
178    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
[2669]179      int i = 0;
[3335]180      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
[2676]181        e.Cancel = true;
[3335]182        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
[2677]183        rowsTextBox.SelectAll();
[2669]184      }
185    }
[2677]186    private void rowsTextBox_Validated(object sender, EventArgs e) {
[3430]187      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
[2677]188      errorProvider.SetError(rowsTextBox, string.Empty);
[2669]189    }
[2677]190    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
[2669]191      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
[2677]192        rowsLabel.Focus();  // set focus on label to validate data
[2676]193      if (e.KeyCode == Keys.Escape) {
[2973]194        rowsTextBox.Text = Content.Rows.ToString();
[2677]195        rowsLabel.Focus();  // set focus on label to validate data
[2676]196      }
[2669]197    }
[2677]198    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
199      int i = 0;
[3335]200      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
[2677]201        e.Cancel = true;
[3335]202        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
[2677]203        columnsTextBox.SelectAll();
204      }
205    }
206    private void columnsTextBox_Validated(object sender, EventArgs e) {
[3430]207      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
[2677]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) {
[2713]214        columnsTextBox.Text = Content.Columns.ToString();
[2677]215        columnsLabel.Focus();  // set focus on label to validate data
216      }
217    }
218    #endregion
219
220    #region DataGridView Events
[2669]221    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
[3328]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        }
[2676]228      }
[2669]229    }
[2676]230    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
[3328]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      }
[2669]237    }
[2676]238    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
239      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
240    }
[3312]241    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
[3337]242      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
243        int rowIndex = virtualRowIndizes[e.RowIndex];
[3335]244        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
[3337]245      }
[3312]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    }
[3314]253
[3643]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
[3314]294    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
[3320]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          }
[3314]304
[3320]305          if (!addToSortedIndizes)
306            sortedColumnIndizes.Clear();
[3314]307
[3320]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        }
[3314]322      }
323    }
324
[3643]325    protected void ClearSorting() {
326      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
327      sortedColumnIndizes.Clear();
328      UpdateSortGlyph();
329    }
330
[3314]331    private void Sort() {
[3444]332      virtualRowIndizes = Sort(sortedColumnIndizes);
333      UpdateSortGlyph();
[3546]334      UpdateRowHeaders();
[3444]335      dataGridView.Invalidate();
336    }
337    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
[3328]338      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
[3444]339      if (sortedColumns.Count() != 0) {
340        rowComparer.SortedIndizes = sortedColumns;
[3346]341        rowComparer.Matrix = Content;
[3314]342        Array.Sort(newSortedIndex, rowComparer);
343      }
[3444]344      return newSortedIndex;
[3328]345    }
346    private void UpdateSortGlyph() {
[3314]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    }
[2677]352    #endregion
[3312]353
[3346]354    public class RowComparer : IComparer<int> {
[3314]355      public RowComparer() {
356      }
[3312]357
[3346]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
[3314]369      public int Compare(int x, int y) {
370        int result = 0;
371        double double1, double2;
372        DateTime dateTime1, dateTime2;
[3444]373        TimeSpan timeSpan1, timeSpan2;
[3314]374        string string1, string2;
375
[3346]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)) {
[3350]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);
[3444]388          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
389            result = timeSpan1.CompareTo(timeSpan2);
[3350]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;
[3314]400        }
401        return result;
402      }
403    }
[3316]404
405    private void ShowHideColumns_Click(object sender, EventArgs e) {
406      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
407    }
[2669]408  }
409}
Note: See TracBrowser for help on using the repository browser.