Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataPreprocessing/HeuristicLab.DataPreprocessing.Views/3.3/DataGridContentView.cs @ 10817

Last change on this file since 10817 was 10817, checked in by sbreuer, 10 years ago
  • added default case to changed event listeners
File size: 17.5 KB
RevLine 
[10539]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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
[10534]22using System;
23using System.Collections.Generic;
[10622]24using System.Drawing;
[10534]25using System.Linq;
[10236]26using System.Windows.Forms;
[10672]27using HeuristicLab.Data;
[10719]28using HeuristicLab.DataPreprocessing.Filter;
[10236]29using HeuristicLab.MainForm;
30
[10558]31namespace HeuristicLab.DataPreprocessing.Views {
[10236]32  [View("Data Grid Content View")]
[10311]33  [Content(typeof(IDataGridContent), true)]
[10583]34  public partial class DataGridContentView : CopyOfStringConvertibleMatrixView {
[10236]35
[10583]36    private bool notOwnEvent = true;
[10762]37    private SearchAndReplaceDialog findAndReplaceDialog;
[10698]38    private IFindPreprocessingItemsIterator searchIterator;
[10672]39    private string currentSearchText;
[10706]40    private Tuple<int, int> currentCell;
[10583]41
[10236]42    public new IDataGridContent Content {
43      get { return (IDataGridContent)base.Content; }
44      set { base.Content = value; }
45    }
46
[10574]47    private IList<int> _highlightedRowIndices;
[10623]48    public IList<int> HighlightedRowIndices {
[10585]49      get { return _highlightedRowIndices; }
50      set {
51        _highlightedRowIndices = value;
52        Refresh();
53      }
[10574]54    }
55
[10623]56    private IDictionary<int, IList<int>> _highlightedCells;
57    public IDictionary<int, IList<int>> HightlightedCells {
58      get { return _highlightedCells; }
59      set {
60        _highlightedCells = value;
61        Refresh();
62      }
63    }
64
[10719]65    private IDictionary<int, IList<int>> _highlightedCellsBackground;
66    public IDictionary<int, IList<int>> HightlightedCellsBackground {
67      get { return _highlightedCellsBackground; }
68      set {
69        _highlightedCellsBackground = value;
70        Refresh();
71      }
72    }
73
[10236]74    public DataGridContentView() {
75      InitializeComponent();
[10380]76      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
[10585]77      dataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(dataGridView_CellPainting);
[10668]78      dataGridView.KeyDown += dataGridView_KeyDown;
[10380]79      contextMenuCell.Items.Add(ShowHideColumns);
[10623]80      _highlightedCells = new Dictionary<int, IList<int>>();
81      _highlightedRowIndices = new List<int>();
[10719]82      _highlightedCellsBackground = new Dictionary<int, IList<int>>();
[10706]83      currentCell = null;
[10804]84      DataGridView.SelectionChanged += DataGridView_SelectionChanged;
[10236]85    }
86
[10804]87    void DataGridView_SelectionChanged(object sender, EventArgs e) {
[10809]88      if (Content != null) {
89        Content.DataGridLogic.SetSelection(GetSelectedCells());
90      }
[10804]91    }
92
[10236]93    protected override void OnContentChanged() {
94      base.OnContentChanged();
[10739]95      if (Content == null && findAndReplaceDialog != null) {
96        findAndReplaceDialog.Close();
97      }
[10236]98    }
99
[10571]100    protected override void RegisterContentEvents() {
101      base.RegisterContentEvents();
102      Content.Changed += Content_Changed;
103    }
104
105    protected override void DeregisterContentEvents() {
106      base.DeregisterContentEvents();
107      Content.Changed -= Content_Changed;
108    }
109
110    void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
[10583]111      if (notOwnEvent) {
[10622]112        switch (e.Type) {
113          case DataPreprocessingChangedEventType.ChangeColumn:
114          case DataPreprocessingChangedEventType.ChangeItem:
115            dataGridView.Refresh();
116            break;
[10817]117          default:
118            OnContentChanged();
119            break;
[10622]120        }
[10583]121      }
[10571]122    }
123
[10583]124    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
[10236]125      if (!dataGridView.ReadOnly) {
126        string errorMessage;
[10246]127        if (Content != null && !Content.DataGridLogic.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex)) {
[10236]128          e.Cancel = true;
129          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
130        }
131      }
132    }
[10253]133
[10583]134    protected override void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
[10585]135      triggersOwnEvent(() => base.dataGridView_CellParsing(sender, e));
[10583]136    }
137
138    protected override void PasteValuesToDataGridView() {
[10585]139      triggersOwnEvent(() => base.PasteValuesToDataGridView());
[10583]140    }
141
[10317]142    protected override void SetEnabledStateOfControls() {
143      base.SetEnabledStateOfControls();
144      rowsTextBox.ReadOnly = true;
145      columnsTextBox.ReadOnly = true;
146    }
147
[10253]148    private void btnApplySort_Click(object sender, System.EventArgs e) {
[10585]149      triggersOwnEvent(() => {
[10809]150        Content.ManipulationLogic.ReOrderToIndices(virtualRowIndices);
[10585]151        OnContentChanged();
152      });
[10253]153    }
[10345]154
[10585]155    private void triggersOwnEvent(Action action) {
156      notOwnEvent = false;
157      action();
158      notOwnEvent = true;
159    }
160
[10698]161    #region FindAndReplaceDialog
[10585]162
[10636]163    private void CreateFindAndReplaceDialog() {
[10762]164      findAndReplaceDialog = new SearchAndReplaceDialog();
[10698]165      findAndReplaceDialog.Show(this);
[10719]166      HightlightedCellsBackground = GetSelectedCells();
167      dataGridView.ClearSelection();
[10636]168      findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
169      findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
170      findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
[10672]171      findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
[10705]172      findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
[10636]173    }
174
[10705]175    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
176      ResetHighlightedCells();
[10719]177      ResetHighlightedCellsBackground();
[10705]178    }
179
[10672]180    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
[10712]181      if (searchIterator != null && searchIterator.GetCurrent() != null) {
[10706]182        Replace(TransformToDictionary(currentCell));
[10672]183      }
[10636]184    }
185
186    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
[10672]187      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
[10636]188    }
189
190    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
[10698]191      if (searchIterator == null || currentSearchText != findAndReplaceDialog.GetSearchText()) {
192        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
193        currentSearchText = findAndReplaceDialog.GetSearchText();
194      }
[10712]195
[10705]196      bool moreOccurences = false;
197      do {
198        currentCell = searchIterator.GetCurrent();
199        moreOccurences = searchIterator.MoveNext();
200      } while (moreOccurences && (currentCell == null || !Content.GetValue(currentCell.Item2, currentCell.Item1).Equals(currentSearchText)));
[10672]201
[10705]202      if (currentCell != null) {
203        HightlightedCells = TransformToDictionary(currentCell);
[10739]204        dataGridView.FirstDisplayedCell = dataGridView[currentCell.Item1, currentCell.Item2];
[10698]205      } else {
[10705]206        ResetHighlightedCells();
[10698]207      }
[10706]208
209      if (!moreOccurences) {
210        searchIterator.Reset();
211      }
[10636]212    }
213
214    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
[10672]215      HightlightedCells = FindAll(findAndReplaceDialog.GetSearchText());
[10636]216    }
217
[10672]218    private IDictionary<int, IList<int>> FindAll(string match) {
[10719]219      bool searchInSelection = HightlightedCellsBackground.Values.Sum(list => list.Count) > 1;
220      var comparisonFilter = new ComparisonFilter(Content.FilterLogic.PreprocessingData, Core.ConstraintOperation.Equal, new StringValue(match), true);
[10672]221      var filters = new List<Filter.IFilter>() { comparisonFilter };
222      var foundCells = new Dictionary<int, IList<int>>();
223      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
224        comparisonFilter.ConstraintColumn = i;
[10785]225        bool[] filteredRows = Content.FilterLogic.Preview(filters, true);
[10672]226        foundCells[i] = filteredRows.Select((value, index) => new { Index = index, Value = value })
227          .Where(pair => pair.Value)
228          .Select(pair => pair.Index)
229          .ToList();
[10719]230        IList<int> selectedList;
231        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
[10739]232          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
233        } else if (searchInSelection) {
[10719]234          foundCells[i].Clear();
235        }
[10672]236      }
237      return foundCells;
238    }
239
240    private void Replace(IDictionary<int, IList<int>> cells) {
241      if (findAndReplaceDialog != null) {
242        switch (findAndReplaceDialog.GetReplaceAction()) {
243          case ReplaceAction.Value:
[10809]244            Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
[10672]245            break;
246          case ReplaceAction.Average:
[10809]247            Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
[10672]248            break;
249          case ReplaceAction.Median:
[10809]250            Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
[10672]251            break;
252          case ReplaceAction.Random:
[10809]253            Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
[10672]254            break;
255          case ReplaceAction.MostCommon:
[10809]256            Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
[10672]257            break;
258          case ReplaceAction.Interpolation:
[10809]259            Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
[10672]260            break;
261        }
262      }
263    }
264
[10698]265    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
[10672]266      var highlightCells = new Dictionary<int, IList<int>>();
[10698]267      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
[10672]268      return highlightCells;
269    }
270
[10705]271    private void ResetHighlightedCells() {
272      HightlightedCells = new Dictionary<int, IList<int>>();
273    }
274
[10719]275    private void ResetHighlightedCellsBackground() {
276      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
277    }
278
[10698]279    #endregion FindAndReplaceDialog
280
[10380]281    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
282      if (Content == null) return;
283      if (e.Button == System.Windows.Forms.MouseButtons.Right) {
284        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
[10769]285          replaceValueOverColumnToolStripMenuItem.Visible = false;
[10627]286          contextMenuCell.Show(MousePosition);
[10380]287        } else {
[10590]288          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
289            dataGridView.ClearSelection();
290            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
291          }
[10812]292
[10621]293          var columnIndices = new HashSet<int>();
294          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
295            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
296          }
[10812]297          averageToolStripMenuItem_Column.Enabled =
298            averageToolStripMenuItem_Selection.Enabled =
299            medianToolStripMenuItem_Column.Enabled =
300            medianToolStripMenuItem_Selection.Enabled =
301            randomToolStripMenuItem_Column.Enabled =
302            randomToolStripMenuItem_Selection.Enabled = !Content.DataGridLogic.AreAllStringColumns(columnIndices);
303
304          smoothingToolStripMenuItem_Column.Enabled =
305            interpolationToolStripMenuItem_Column.Enabled = !(e.RowIndex == 0 || e.RowIndex == Content.Rows)
306            && !Content.DataGridLogic.AreAllStringColumns(columnIndices);
307
[10769]308          replaceValueOverColumnToolStripMenuItem.Visible = true;
[10380]309          contextMenuCell.Show(MousePosition);
310        }
311      }
312    }
313
[10585]314    protected void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
315      if (Content == null) return;
316      if (e.RowIndex < 0) return;
317      if (e.ColumnIndex < 0) return;
318      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
319      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
[10659]320      if (HighlightedRowIndices == null && HightlightedCells == null) return;
[10574]321
[10585]322      int rowIndex = virtualRowIndices[e.RowIndex];
[10574]323
[10585]324      Color backColor = e.CellStyle.BackColor;
[10574]325
[10719]326      if (HightlightedCellsBackground.ContainsKey(e.ColumnIndex) && HightlightedCellsBackground[e.ColumnIndex].Contains(e.RowIndex)) {
327        backColor = Color.LightGray;
328      }
[10659]329      if (HighlightedRowIndices.Contains(rowIndex) || HightlightedCells.ContainsKey(e.ColumnIndex) && HightlightedCells[e.ColumnIndex].Contains(e.RowIndex)) {
[10719]330        backColor = Color.LightGreen;
[10585]331      }
[10574]332
[10585]333      using (Brush backColorBrush = new SolidBrush(backColor)) {
334        Rectangle bounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
335        e.Graphics.FillRectangle(backColorBrush, bounds);
336      }
[10712]337
[10585]338      using (Brush gridBrush = new SolidBrush(Color.LightGray)) {
339        Pen gridLinePen = new Pen(gridBrush);
340        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
341               e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
342               e.CellBounds.Bottom - 1);
343        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
344            e.CellBounds.Top, e.CellBounds.Right - 1,
345            e.CellBounds.Bottom);
346      }
347
348      e.PaintContent(e.CellBounds);
349      e.Handled = true;
[10574]350    }
351
[10668]352    void dataGridView_KeyDown(object sender, KeyEventArgs e) {
353      var selectedRows = dataGridView.SelectedRows;
354      if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
355        List<int> rows = new List<int>();
356        for (int i = 0; i < selectedRows.Count; ++i) {
357          rows.Add(selectedRows[i].Index);
358        }
359        triggersOwnEvent(() => {
360          Content.DataGridLogic.DeleteRow(rows);
361          OnContentChanged();
362        });
363      } else if (e.Control && e.KeyCode == Keys.F) {
364        CreateFindAndReplaceDialog();
365        findAndReplaceDialog.ActivateSearch();
366      } else if (e.Control && e.KeyCode == Keys.R) {
367        CreateFindAndReplaceDialog();
368        findAndReplaceDialog.ActivateReplace();
369      }
370    }
371
[10345]372    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
373      btnApplySort.Enabled = sortedColumns.Any();
374      return base.Sort(sortedColumns);
375    }
376
377    protected override void ClearSorting() {
378      btnApplySort.Enabled = false;
379      base.ClearSorting();
380    }
[10380]381
[10672]382    private IDictionary<int, IList<int>> GetSelectedCells() {
383      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
[10590]384      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
[10622]385        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
386        if (!selectedCells.ContainsKey(columnIndex)) {
387          selectedCells.Add(columnIndex, new List<int>());
[10590]388        }
389        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
390      }
391      return selectedCells;
392    }
393
[10769]394    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
[10812]395      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
[10380]396    }
[10809]397    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
398      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
399    }
[10380]400
[10769]401    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
[10809]402      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
[10380]403    }
[10809]404    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
405      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
406    }
[10380]407
[10769]408    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
[10809]409      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
[10380]410    }
[10809]411    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
412      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
413    }
[10380]414
[10769]415    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
[10809]416      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
[10380]417    }
[10809]418    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
419      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
420    }
[10380]421
[10769]422    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
[10809]423      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
[10380]424    }
[10769]425    private void ReplaceWithInterpolation_Selection_Click(object sender, EventArgs e) {
[10809]426      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
[10769]427    }
428
429    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
430    }
431
[10764]432    private void btnSearch_Click(object sender, EventArgs e) {
[10762]433      CreateFindAndReplaceDialog();
434      findAndReplaceDialog.ActivateSearch();
435    }
436
437    private void btnReplace_Click(object sender, EventArgs e) {
438      CreateFindAndReplaceDialog();
439      findAndReplaceDialog.ActivateReplace();
440    }
[10236]441  }
442}
Note: See TracBrowser for help on using the repository browser.