Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3633 was 3566, checked in by mkommend, 15 years ago

removed ctors with contents in all views (ticket #972)

File size: 14.8 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();
109      Sort();
[2713]110      rowsTextBox.Text = Content.Rows.ToString();
[2973]111      rowsTextBox.Enabled = true;
[2713]112      columnsTextBox.Text = Content.Columns.ToString();
[2973]113      columnsTextBox.Enabled = true;
[3324]114      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
[3335]115      //DataGridViews with Rows but no columns are not allowed !
[3431]116      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
[3335]117        Content.Rows = dataGridView.RowCount;
118      else
119        dataGridView.RowCount = Content.Rows;
[3431]120      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
[3335]121        Content.Columns = dataGridView.ColumnCount;
122      else
123        dataGridView.ColumnCount = Content.Columns;
[3346]124
[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
254    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
[3320]255      if (Content != null) {
256        if (e.Button == MouseButtons.Left && Content.SortableView) {
257          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
258          SortOrder newSortOrder = SortOrder.Ascending;
259          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
260            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
261            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
262            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
263          }
[3314]264
[3320]265          if (!addToSortedIndizes)
266            sortedColumnIndizes.Clear();
[3314]267
[3320]268          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
269            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
270            if (newSortOrder != SortOrder.None)
271              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
272            else
273              sortedColumnIndizes.RemoveAt(sortedIndex);
274          } else
275            if (newSortOrder != SortOrder.None)
276              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
277          Sort();
278        } else if (e.Button == MouseButtons.Right) {
279          if (Content.ColumnNames.Count() != 0)
280            contextMenu.Show(MousePosition);
281        }
[3314]282      }
283    }
284
285    private void Sort() {
[3444]286      virtualRowIndizes = Sort(sortedColumnIndizes);
287      UpdateSortGlyph();
[3546]288      UpdateRowHeaders();
[3444]289      dataGridView.Invalidate();
290    }
291    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
[3328]292      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
[3444]293      if (sortedColumns.Count() != 0) {
294        rowComparer.SortedIndizes = sortedColumns;
[3346]295        rowComparer.Matrix = Content;
[3314]296        Array.Sort(newSortedIndex, rowComparer);
297      }
[3444]298      return newSortedIndex;
[3328]299    }
300    private void UpdateSortGlyph() {
[3314]301      foreach (DataGridViewColumn col in this.dataGridView.Columns)
302        col.HeaderCell.SortGlyphDirection = SortOrder.None;
303      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
304        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
305    }
[2677]306    #endregion
[3312]307
[3346]308    public class RowComparer : IComparer<int> {
[3314]309      public RowComparer() {
310      }
[3312]311
[3346]312      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
313      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
314        get { return this.sortedIndizes; }
315        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
316      }
317      private IStringConvertibleMatrix matrix;
318      public IStringConvertibleMatrix Matrix {
319        get { return this.matrix; }
320        set { this.matrix = value; }
321      }
322
[3314]323      public int Compare(int x, int y) {
324        int result = 0;
325        double double1, double2;
326        DateTime dateTime1, dateTime2;
[3444]327        TimeSpan timeSpan1, timeSpan2;
[3314]328        string string1, string2;
329
[3346]330        if (matrix == null)
331          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
332        if (sortedIndizes == null)
333          return 0;
334
335        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
[3350]336          string1 = matrix.GetValue(x, pair.Key);
337          string2 = matrix.GetValue(y, pair.Key);
338          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
339            result = double1.CompareTo(double2);
340          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
341            result = dateTime1.CompareTo(dateTime2);
[3444]342          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
343            result = timeSpan1.CompareTo(timeSpan2);
[3350]344          else {
345            if (string1 != null)
346              result = string1.CompareTo(string2);
347            else if (string2 != null)
348              result = string2.CompareTo(string1) * -1;
349          }
350          if (pair.Value == SortOrder.Descending)
351            result *= -1;
352          if (result != 0)
353            return result;
[3314]354        }
355        return result;
356      }
357    }
[3316]358
359    private void ShowHideColumns_Click(object sender, EventArgs e) {
360      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
361    }
[2669]362  }
363}
Note: See TracBrowser for help on using the repository browser.