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
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Data;
28using HeuristicLab.DataPreprocessing.Filter;
29using HeuristicLab.MainForm;
30
31namespace HeuristicLab.DataPreprocessing.Views {
32  [View("Data Grid Content View")]
33  [Content(typeof(IDataGridContent), true)]
34  public partial class DataGridContentView : CopyOfStringConvertibleMatrixView {
35
36    private bool notOwnEvent = true;
37    private SearchAndReplaceDialog findAndReplaceDialog;
38    private IFindPreprocessingItemsIterator searchIterator;
39    private string currentSearchText;
40    private Tuple<int, int> currentCell;
41
42    public new IDataGridContent Content {
43      get { return (IDataGridContent)base.Content; }
44      set { base.Content = value; }
45    }
46
47    private IList<int> _highlightedRowIndices;
48    public IList<int> HighlightedRowIndices {
49      get { return _highlightedRowIndices; }
50      set {
51        _highlightedRowIndices = value;
52        Refresh();
53      }
54    }
55
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
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
74    public DataGridContentView() {
75      InitializeComponent();
76      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
77      dataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(dataGridView_CellPainting);
78      dataGridView.KeyDown += dataGridView_KeyDown;
79      contextMenuCell.Items.Add(ShowHideColumns);
80      _highlightedCells = new Dictionary<int, IList<int>>();
81      _highlightedRowIndices = new List<int>();
82      _highlightedCellsBackground = new Dictionary<int, IList<int>>();
83      currentCell = null;
84      DataGridView.SelectionChanged += DataGridView_SelectionChanged;
85    }
86
87    void DataGridView_SelectionChanged(object sender, EventArgs e) {
88      if (Content != null) {
89        Content.DataGridLogic.SetSelection(GetSelectedCells());
90      }
91    }
92
93    protected override void OnContentChanged() {
94      base.OnContentChanged();
95      if (Content == null && findAndReplaceDialog != null) {
96        findAndReplaceDialog.Close();
97      }
98    }
99
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) {
111      if (notOwnEvent) {
112        switch (e.Type) {
113          case DataPreprocessingChangedEventType.ChangeColumn:
114          case DataPreprocessingChangedEventType.ChangeItem:
115            dataGridView.Refresh();
116            break;
117          default:
118            OnContentChanged();
119            break;
120        }
121      }
122    }
123
124    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
125      if (!dataGridView.ReadOnly) {
126        string errorMessage;
127        if (Content != null && !Content.DataGridLogic.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex)) {
128          e.Cancel = true;
129          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
130        }
131      }
132    }
133
134    protected override void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
135      triggersOwnEvent(() => base.dataGridView_CellParsing(sender, e));
136    }
137
138    protected override void PasteValuesToDataGridView() {
139      triggersOwnEvent(() => base.PasteValuesToDataGridView());
140    }
141
142    protected override void SetEnabledStateOfControls() {
143      base.SetEnabledStateOfControls();
144      rowsTextBox.ReadOnly = true;
145      columnsTextBox.ReadOnly = true;
146    }
147
148    private void btnApplySort_Click(object sender, System.EventArgs e) {
149      triggersOwnEvent(() => {
150        Content.ManipulationLogic.ReOrderToIndices(virtualRowIndices);
151        OnContentChanged();
152      });
153    }
154
155    private void triggersOwnEvent(Action action) {
156      notOwnEvent = false;
157      action();
158      notOwnEvent = true;
159    }
160
161    #region FindAndReplaceDialog
162
163    private void CreateFindAndReplaceDialog() {
164      findAndReplaceDialog = new SearchAndReplaceDialog();
165      findAndReplaceDialog.Show(this);
166      HightlightedCellsBackground = GetSelectedCells();
167      dataGridView.ClearSelection();
168      findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
169      findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
170      findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
171      findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
172      findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
173    }
174
175    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
176      ResetHighlightedCells();
177      ResetHighlightedCellsBackground();
178    }
179
180    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
181      if (searchIterator != null && searchIterator.GetCurrent() != null) {
182        Replace(TransformToDictionary(currentCell));
183      }
184    }
185
186    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
187      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
188    }
189
190    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
191      if (searchIterator == null || currentSearchText != findAndReplaceDialog.GetSearchText()) {
192        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
193        currentSearchText = findAndReplaceDialog.GetSearchText();
194      }
195
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)));
201
202      if (currentCell != null) {
203        HightlightedCells = TransformToDictionary(currentCell);
204        dataGridView.FirstDisplayedCell = dataGridView[currentCell.Item1, currentCell.Item2];
205      } else {
206        ResetHighlightedCells();
207      }
208
209      if (!moreOccurences) {
210        searchIterator.Reset();
211      }
212    }
213
214    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
215      HightlightedCells = FindAll(findAndReplaceDialog.GetSearchText());
216    }
217
218    private IDictionary<int, IList<int>> FindAll(string match) {
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);
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;
225        bool[] filteredRows = Content.FilterLogic.Preview(filters, true);
226        foundCells[i] = filteredRows.Select((value, index) => new { Index = index, Value = value })
227          .Where(pair => pair.Value)
228          .Select(pair => pair.Index)
229          .ToList();
230        IList<int> selectedList;
231        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
232          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
233        } else if (searchInSelection) {
234          foundCells[i].Clear();
235        }
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:
244            Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
245            break;
246          case ReplaceAction.Average:
247            Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
248            break;
249          case ReplaceAction.Median:
250            Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
251            break;
252          case ReplaceAction.Random:
253            Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
254            break;
255          case ReplaceAction.MostCommon:
256            Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
257            break;
258          case ReplaceAction.Interpolation:
259            Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
260            break;
261        }
262      }
263    }
264
265    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
266      var highlightCells = new Dictionary<int, IList<int>>();
267      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
268      return highlightCells;
269    }
270
271    private void ResetHighlightedCells() {
272      HightlightedCells = new Dictionary<int, IList<int>>();
273    }
274
275    private void ResetHighlightedCellsBackground() {
276      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
277    }
278
279    #endregion FindAndReplaceDialog
280
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) {
285          replaceValueOverColumnToolStripMenuItem.Visible = false;
286          contextMenuCell.Show(MousePosition);
287        } else {
288          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
289            dataGridView.ClearSelection();
290            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
291          }
292
293          var columnIndices = new HashSet<int>();
294          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
295            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
296          }
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
308          replaceValueOverColumnToolStripMenuItem.Visible = true;
309          contextMenuCell.Show(MousePosition);
310        }
311      }
312    }
313
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;
320      if (HighlightedRowIndices == null && HightlightedCells == null) return;
321
322      int rowIndex = virtualRowIndices[e.RowIndex];
323
324      Color backColor = e.CellStyle.BackColor;
325
326      if (HightlightedCellsBackground.ContainsKey(e.ColumnIndex) && HightlightedCellsBackground[e.ColumnIndex].Contains(e.RowIndex)) {
327        backColor = Color.LightGray;
328      }
329      if (HighlightedRowIndices.Contains(rowIndex) || HightlightedCells.ContainsKey(e.ColumnIndex) && HightlightedCells[e.ColumnIndex].Contains(e.RowIndex)) {
330        backColor = Color.LightGreen;
331      }
332
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      }
337
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;
350    }
351
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
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    }
381
382    private IDictionary<int, IList<int>> GetSelectedCells() {
383      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
384      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
385        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
386        if (!selectedCells.ContainsKey(columnIndex)) {
387          selectedCells.Add(columnIndex, new List<int>());
388        }
389        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
390      }
391      return selectedCells;
392    }
393
394    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
395      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
396    }
397    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
398      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
399    }
400
401    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
402      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
403    }
404    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
405      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
406    }
407
408    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
409      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
410    }
411    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
412      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
413    }
414
415    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
416      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
417    }
418    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
419      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
420    }
421
422    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
423      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
424    }
425    private void ReplaceWithInterpolation_Selection_Click(object sender, EventArgs e) {
426      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
427    }
428
429    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
430    }
431
432    private void btnSearch_Click(object sender, EventArgs e) {
433      CreateFindAndReplaceDialog();
434      findAndReplaceDialog.ActivateSearch();
435    }
436
437    private void btnReplace_Click(object sender, EventArgs e) {
438      CreateFindAndReplaceDialog();
439      findAndReplaceDialog.ActivateReplace();
440    }
441  }
442}
Note: See TracBrowser for help on using the repository browser.