Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3494 was 3454, checked in by swagner, 15 years ago

Adapted views according the new read-only property (#973)

File size: 15.0 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    }
[3048]63    public StringConvertibleMatrixView(IStringConvertibleMatrix content)
[2669]64      : this() {
[2727]65      Content = content;
[2669]66    }
67
[2713]68    protected override void DeregisterContentEvents() {
69      Content.ItemChanged -= new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
70      Content.Reset -= new EventHandler(Content_Reset);
[3320]71      Content.ColumnNamesChanged -= new EventHandler(Content_ColumnNamesChanged);
72      Content.RowNamesChanged -= new EventHandler(Content_RowNamesChanged);
[2713]73      base.DeregisterContentEvents();
[2669]74    }
[2713]75    protected override void RegisterContentEvents() {
76      base.RegisterContentEvents();
77      Content.ItemChanged += new EventHandler<EventArgs<int, int>>(Content_ItemChanged);
78      Content.Reset += new EventHandler(Content_Reset);
[3320]79      Content.ColumnNamesChanged += new EventHandler(Content_ColumnNamesChanged);
80      Content.RowNamesChanged += new EventHandler(Content_RowNamesChanged);
[2669]81    }
82
[2713]83    protected override void OnContentChanged() {
84      base.OnContentChanged();
85      if (Content == null) {
[3048]86        Caption = "StringConvertibleMatrix View";
[2677]87        rowsTextBox.Text = "";
88        columnsTextBox.Text = "";
[2669]89        dataGridView.Rows.Clear();
[2677]90        dataGridView.Columns.Clear();
[3324]91        virtualRowIndizes = new int[0];
[2669]92      } else {
[3048]93        Caption = "StringConvertibleMatrix (" + Content.GetType().Name + ")";
[2713]94        UpdateData();
[2669]95      }
[3362]96      SetEnabledStateOfControls();
[2669]97    }
[3350]98    protected override void OnReadOnlyChanged() {
99      base.OnReadOnlyChanged();
[3362]100      SetEnabledStateOfControls();
[3350]101    }
[3362]102    private void SetEnabledStateOfControls() {
[3454]103      rowsTextBox.Enabled = Content != null;
104      columnsTextBox.Enabled = Content != null;
105      dataGridView.Enabled = Content != null;
106      rowsTextBox.ReadOnly = ReadOnly;
107      columnsTextBox.ReadOnly = ReadOnly;
108      dataGridView.ReadOnly = ReadOnly;
[3350]109    }
[2669]110
[2713]111    private void UpdateData() {
[3328]112      sortedColumnIndizes.Clear();
113      Sort();
[2713]114      rowsTextBox.Text = Content.Rows.ToString();
[2973]115      rowsTextBox.Enabled = true;
[2713]116      columnsTextBox.Text = Content.Columns.ToString();
[2973]117      columnsTextBox.Enabled = true;
[3324]118      virtualRowIndizes = Enumerable.Range(0, Content.Rows).ToArray();
[3335]119      //DataGridViews with Rows but no columns are not allowed !
[3431]120      if (Content.Rows == 0 && dataGridView.RowCount != Content.Rows && !Content.ReadOnly)
[3335]121        Content.Rows = dataGridView.RowCount;
122      else
123        dataGridView.RowCount = Content.Rows;
[3431]124      if (Content.Columns == 0 && dataGridView.ColumnCount != Content.Columns && !Content.ReadOnly)
[3335]125        Content.Columns = dataGridView.ColumnCount;
126      else
127        dataGridView.ColumnCount = Content.Columns;
[3346]128
[3328]129      UpdateRowHeaders();
130      UpdateColumnHeaders();
[3346]131      dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.ColumnHeader);
132      dataGridView.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders);
[2669]133      dataGridView.Enabled = true;
134    }
135
[3312]136    private void UpdateColumnHeaders() {
137      for (int i = 0; i < Content.Columns; i++) {
138        if (Content.ColumnNames.Count() != 0)
139          dataGridView.Columns[i].HeaderText = Content.ColumnNames.ElementAt(i);
140        else
[3346]141          dataGridView.Columns[i].HeaderText = "Column " + (i + 1);
[3312]142      }
143      dataGridView.Invalidate();
144    }
145
146    private void UpdateRowHeaders() {
147      for (int i = dataGridView.FirstDisplayedScrollingRowIndex; i < dataGridView.FirstDisplayedScrollingRowIndex + dataGridView.DisplayedRowCount(true); i++) {
148        if (Content.RowNames.Count() != 0)
149          dataGridView.Rows[i].HeaderCell.Value = Content.RowNames.ElementAt(i);
[3314]150        else
[3346]151          dataGridView.Rows[i].HeaderCell.Value = "Row " + (i + 1);
[3312]152      }
153      dataGridView.Invalidate();
154    }
155
[3320]156    private void Content_RowNamesChanged(object sender, EventArgs e) {
[3328]157      if (InvokeRequired)
158        Invoke(new EventHandler(Content_RowNamesChanged), sender, e);
159      else
160        UpdateRowHeaders();
[3320]161    }
162    private void Content_ColumnNamesChanged(object sender, EventArgs e) {
[3328]163      if (InvokeRequired)
164        Invoke(new EventHandler(Content_ColumnNamesChanged), sender, e);
165      else
166        UpdateColumnHeaders();
[3320]167    }
[2713]168    private void Content_ItemChanged(object sender, EventArgs<int, int> e) {
[2669]169      if (InvokeRequired)
[2713]170        Invoke(new EventHandler<EventArgs<int, int>>(Content_ItemChanged), sender, e);
[3328]171      else
[3335]172        dataGridView.InvalidateCell(e.Value2, e.Value);
[2669]173    }
[2713]174    private void Content_Reset(object sender, EventArgs e) {
[2669]175      if (InvokeRequired)
[2713]176        Invoke(new EventHandler(Content_Reset), sender, e);
[2669]177      else
[2713]178        UpdateData();
[2669]179    }
180
[2677]181    #region TextBox Events
182    private void rowsTextBox_Validating(object sender, CancelEventArgs e) {
[2669]183      int i = 0;
[3335]184      if (!int.TryParse(rowsTextBox.Text, out i) || (i <= 0)) {
[2676]185        e.Cancel = true;
[3335]186        errorProvider.SetError(rowsTextBox, "Invalid Number of Rows (Valid values are positive integers larger than 0)");
[2677]187        rowsTextBox.SelectAll();
[2669]188      }
189    }
[2677]190    private void rowsTextBox_Validated(object sender, EventArgs e) {
[3430]191      if (!Content.ReadOnly) Content.Rows = int.Parse(rowsTextBox.Text);
[2677]192      errorProvider.SetError(rowsTextBox, string.Empty);
[2669]193    }
[2677]194    private void rowsTextBox_KeyDown(object sender, KeyEventArgs e) {
[2669]195      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
[2677]196        rowsLabel.Focus();  // set focus on label to validate data
[2676]197      if (e.KeyCode == Keys.Escape) {
[2973]198        rowsTextBox.Text = Content.Rows.ToString();
[2677]199        rowsLabel.Focus();  // set focus on label to validate data
[2676]200      }
[2669]201    }
[2677]202    private void columnsTextBox_Validating(object sender, CancelEventArgs e) {
203      int i = 0;
[3335]204      if (!int.TryParse(columnsTextBox.Text, out i) || (i <= 0)) {
[2677]205        e.Cancel = true;
[3335]206        errorProvider.SetError(columnsTextBox, "Invalid Number of Columns (Valid values are positive integers larger than 0)");
[2677]207        columnsTextBox.SelectAll();
208      }
209    }
210    private void columnsTextBox_Validated(object sender, EventArgs e) {
[3430]211      if (!Content.ReadOnly) Content.Columns = int.Parse(columnsTextBox.Text);
[2677]212      errorProvider.SetError(columnsTextBox, string.Empty);
213    }
214    private void columnsTextBox_KeyDown(object sender, KeyEventArgs e) {
215      if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
216        columnsLabel.Focus();  // set focus on label to validate data
217      if (e.KeyCode == Keys.Escape) {
[2713]218        columnsTextBox.Text = Content.Columns.ToString();
[2677]219        columnsLabel.Focus();  // set focus on label to validate data
220      }
221    }
222    #endregion
223
224    #region DataGridView Events
[2669]225    private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
[3328]226      if (!dataGridView.ReadOnly) {
227        string errorMessage;
228        if (!Content.Validate(e.FormattedValue.ToString(), out errorMessage)) {
229          e.Cancel = true;
230          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
231        }
[2676]232      }
[2669]233    }
[2676]234    private void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
[3328]235      if (!dataGridView.ReadOnly) {
236        string value = e.Value.ToString();
237        int rowIndex = virtualRowIndizes[e.RowIndex];
238        e.ParsingApplied = Content.SetValue(value, rowIndex, e.ColumnIndex);
239        if (e.ParsingApplied) e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
240      }
[2669]241    }
[2676]242    private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e) {
243      dataGridView.Rows[e.RowIndex].ErrorText = string.Empty;
244    }
[3312]245    private void dataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) {
[3337]246      if (e.RowIndex < Content.Rows && e.ColumnIndex < Content.Columns) {
247        int rowIndex = virtualRowIndizes[e.RowIndex];
[3335]248        e.Value = Content.GetValue(rowIndex, e.ColumnIndex);
[3337]249      }
[3312]250    }
251    private void dataGridView_Scroll(object sender, ScrollEventArgs e) {
252      UpdateRowHeaders();
253    }
254    private void dataGridView_Resize(object sender, EventArgs e) {
255      UpdateRowHeaders();
256    }
[3314]257
258    private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
[3320]259      if (Content != null) {
260        if (e.Button == MouseButtons.Left && Content.SortableView) {
261          bool addToSortedIndizes = (Control.ModifierKeys & Keys.Control) == Keys.Control;
262          SortOrder newSortOrder = SortOrder.Ascending;
263          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
264            SortOrder oldSortOrder = sortedColumnIndizes.Where(x => x.Key == e.ColumnIndex).First().Value;
265            int enumLength = Enum.GetValues(typeof(SortOrder)).Length;
266            newSortOrder = oldSortOrder = (SortOrder)Enum.Parse(typeof(SortOrder), ((((int)oldSortOrder) + 1) % enumLength).ToString());
267          }
[3314]268
[3320]269          if (!addToSortedIndizes)
270            sortedColumnIndizes.Clear();
[3314]271
[3320]272          if (sortedColumnIndizes.Any(x => x.Key == e.ColumnIndex)) {
273            int sortedIndex = sortedColumnIndizes.FindIndex(x => x.Key == e.ColumnIndex);
274            if (newSortOrder != SortOrder.None)
275              sortedColumnIndizes[sortedIndex] = new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder);
276            else
277              sortedColumnIndizes.RemoveAt(sortedIndex);
278          } else
279            if (newSortOrder != SortOrder.None)
280              sortedColumnIndizes.Add(new KeyValuePair<int, SortOrder>(e.ColumnIndex, newSortOrder));
281          Sort();
282        } else if (e.Button == MouseButtons.Right) {
283          if (Content.ColumnNames.Count() != 0)
284            contextMenu.Show(MousePosition);
285        }
[3314]286      }
287    }
288
289    private void Sort() {
[3444]290      virtualRowIndizes = Sort(sortedColumnIndizes);
291      UpdateSortGlyph();
292      dataGridView.Invalidate();
293    }
294    protected virtual int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
[3328]295      int[] newSortedIndex = Enumerable.Range(0, Content.Rows).ToArray();
[3444]296      if (sortedColumns.Count() != 0) {
297        rowComparer.SortedIndizes = sortedColumns;
[3346]298        rowComparer.Matrix = Content;
[3314]299        Array.Sort(newSortedIndex, rowComparer);
300      }
[3444]301      return newSortedIndex;
[3328]302    }
303    private void UpdateSortGlyph() {
[3314]304      foreach (DataGridViewColumn col in this.dataGridView.Columns)
305        col.HeaderCell.SortGlyphDirection = SortOrder.None;
306      foreach (KeyValuePair<int, SortOrder> p in sortedColumnIndizes)
307        this.dataGridView.Columns[p.Key].HeaderCell.SortGlyphDirection = p.Value;
308    }
[2677]309    #endregion
[3312]310
[3346]311    public class RowComparer : IComparer<int> {
[3314]312      public RowComparer() {
313      }
[3312]314
[3346]315      private List<KeyValuePair<int, SortOrder>> sortedIndizes;
316      public IEnumerable<KeyValuePair<int, SortOrder>> SortedIndizes {
317        get { return this.sortedIndizes; }
318        set { sortedIndizes = new List<KeyValuePair<int, SortOrder>>(value); }
319      }
320      private IStringConvertibleMatrix matrix;
321      public IStringConvertibleMatrix Matrix {
322        get { return this.matrix; }
323        set { this.matrix = value; }
324      }
325
[3314]326      public int Compare(int x, int y) {
327        int result = 0;
328        double double1, double2;
329        DateTime dateTime1, dateTime2;
[3444]330        TimeSpan timeSpan1, timeSpan2;
[3314]331        string string1, string2;
332
[3346]333        if (matrix == null)
334          throw new InvalidOperationException("Could not sort IStringConvertibleMatrix if the matrix member is null.");
335        if (sortedIndizes == null)
336          return 0;
337
338        foreach (KeyValuePair<int, SortOrder> pair in sortedIndizes.Where(p => p.Value != SortOrder.None)) {
[3350]339          string1 = matrix.GetValue(x, pair.Key);
340          string2 = matrix.GetValue(y, pair.Key);
341          if (double.TryParse(string1, out double1) && double.TryParse(string2, out double2))
342            result = double1.CompareTo(double2);
343          else if (DateTime.TryParse(string1, out dateTime1) && DateTime.TryParse(string2, out dateTime2))
344            result = dateTime1.CompareTo(dateTime2);
[3444]345          else if (TimeSpan.TryParse(string1, out timeSpan1) && TimeSpan.TryParse(string2, out timeSpan2))
346            result = timeSpan1.CompareTo(timeSpan2);
[3350]347          else {
348            if (string1 != null)
349              result = string1.CompareTo(string2);
350            else if (string2 != null)
351              result = string2.CompareTo(string1) * -1;
352          }
353          if (pair.Value == SortOrder.Descending)
354            result *= -1;
355          if (result != 0)
356            return result;
[3314]357        }
358        return result;
359      }
360    }
[3316]361
362    private void ShowHideColumns_Click(object sender, EventArgs e) {
363      new ColumnsVisibilityDialog(this.dataGridView.Columns.Cast<DataGridViewColumn>()).ShowDialog();
364    }
[2669]365  }
366}
Note: See TracBrowser for help on using the repository browser.