Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10844 was 10844, checked in by rstoll, 10 years ago
  • FilterResult was inversed at some point (true meaning it is filtered, not displayed respectively and thus not found and false means found)
  • Fixed that search applies a preview (data shall not be filtered, it only uses the FilterLogic)
File size: 17.6 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.GetFilterResult(filters, true);
226        var foundIndices = new List<int>();
227        for (int idx = 0; idx < filteredRows.Length; ++idx) {
228          var notFilteredThusFound = !filteredRows[idx];
229          if (notFilteredThusFound) {
230            foundIndices.Add(idx);
231          }
232        }
233        foundCells[i] = foundIndices;
234        IList<int> selectedList;
235        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
236          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
237        } else if (searchInSelection) {
238          foundCells[i].Clear();
239        }
240      }
241      return foundCells;
242    }
243
244    private void Replace(IDictionary<int, IList<int>> cells) {
245      if (findAndReplaceDialog != null) {
246        switch (findAndReplaceDialog.GetReplaceAction()) {
247          case ReplaceAction.Value:
248            Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
249            break;
250          case ReplaceAction.Average:
251            Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
252            break;
253          case ReplaceAction.Median:
254            Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
255            break;
256          case ReplaceAction.Random:
257            Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
258            break;
259          case ReplaceAction.MostCommon:
260            Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
261            break;
262          case ReplaceAction.Interpolation:
263            Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
264            break;
265        }
266      }
267    }
268
269    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
270      var highlightCells = new Dictionary<int, IList<int>>();
271      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
272      return highlightCells;
273    }
274
275    private void ResetHighlightedCells() {
276      HightlightedCells = new Dictionary<int, IList<int>>();
277    }
278
279    private void ResetHighlightedCellsBackground() {
280      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
281    }
282
283    #endregion FindAndReplaceDialog
284
285    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
286      if (Content == null) return;
287      if (e.Button == System.Windows.Forms.MouseButtons.Right) {
288        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
289          replaceValueOverColumnToolStripMenuItem.Visible = false;
290          contextMenuCell.Show(MousePosition);
291        } else {
292          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
293            dataGridView.ClearSelection();
294            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
295          }
296
297          var columnIndices = new HashSet<int>();
298          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
299            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
300          }
301          averageToolStripMenuItem_Column.Enabled =
302            averageToolStripMenuItem_Selection.Enabled =
303            medianToolStripMenuItem_Column.Enabled =
304            medianToolStripMenuItem_Selection.Enabled =
305            randomToolStripMenuItem_Column.Enabled =
306            randomToolStripMenuItem_Selection.Enabled = !Content.DataGridLogic.AreAllStringColumns(columnIndices);
307
308          smoothingToolStripMenuItem_Column.Enabled =
309            interpolationToolStripMenuItem_Column.Enabled = !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, 0])
310            && !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, Content.Rows - 1])
311            && !Content.DataGridLogic.AreAllStringColumns(columnIndices);
312
313          replaceValueOverColumnToolStripMenuItem.Visible = true;
314          contextMenuCell.Show(MousePosition);
315        }
316      }
317    }
318
319    protected void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
320      if (Content == null) return;
321      if (e.RowIndex < 0) return;
322      if (e.ColumnIndex < 0) return;
323      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
324      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
325      if (HighlightedRowIndices == null && HightlightedCells == null) return;
326
327      int rowIndex = virtualRowIndices[e.RowIndex];
328
329      Color backColor = e.CellStyle.BackColor;
330
331      if (HightlightedCellsBackground.ContainsKey(e.ColumnIndex) && HightlightedCellsBackground[e.ColumnIndex].Contains(e.RowIndex)) {
332        backColor = Color.LightGray;
333      }
334      if (HighlightedRowIndices.Contains(rowIndex) || HightlightedCells.ContainsKey(e.ColumnIndex) && HightlightedCells[e.ColumnIndex].Contains(e.RowIndex)) {
335        backColor = Color.LightGreen;
336      }
337
338      using (Brush backColorBrush = new SolidBrush(backColor)) {
339        Rectangle bounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
340        e.Graphics.FillRectangle(backColorBrush, bounds);
341      }
342
343      using (Brush gridBrush = new SolidBrush(Color.LightGray)) {
344        Pen gridLinePen = new Pen(gridBrush);
345        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
346               e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
347               e.CellBounds.Bottom - 1);
348        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
349            e.CellBounds.Top, e.CellBounds.Right - 1,
350            e.CellBounds.Bottom);
351      }
352
353      e.PaintContent(e.CellBounds);
354      e.Handled = true;
355    }
356
357    void dataGridView_KeyDown(object sender, KeyEventArgs e) {
358      var selectedRows = dataGridView.SelectedRows;
359      if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
360        List<int> rows = new List<int>();
361        for (int i = 0; i < selectedRows.Count; ++i) {
362          rows.Add(selectedRows[i].Index);
363        }
364        triggersOwnEvent(() => {
365          Content.DataGridLogic.DeleteRow(rows);
366          OnContentChanged();
367        });
368      } else if (e.Control && e.KeyCode == Keys.F) {
369        CreateFindAndReplaceDialog();
370        findAndReplaceDialog.ActivateSearch();
371      } else if (e.Control && e.KeyCode == Keys.R) {
372        CreateFindAndReplaceDialog();
373        findAndReplaceDialog.ActivateReplace();
374      }
375    }
376
377    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
378      btnApplySort.Enabled = sortedColumns.Any();
379      return base.Sort(sortedColumns);
380    }
381
382    protected override void ClearSorting() {
383      btnApplySort.Enabled = false;
384      base.ClearSorting();
385    }
386
387    private IDictionary<int, IList<int>> GetSelectedCells() {
388      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
389      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
390        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
391        if (!selectedCells.ContainsKey(columnIndex)) {
392          selectedCells.Add(columnIndex, new List<int>());
393        }
394        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
395      }
396      return selectedCells;
397    }
398
399    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
400      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
401    }
402    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
403      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
404    }
405
406    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
407      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
408    }
409    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
410      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
411    }
412
413    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
414      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
415    }
416    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
417      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
418    }
419
420    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
421      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
422    }
423    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
424      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
425    }
426
427    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
428      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
429    }
430
431    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
432      Content.ManipulationLogic.ReplaceIndicesBySmoothing(GetSelectedCells());
433    }
434
435    private void btnSearch_Click(object sender, EventArgs e) {
436      CreateFindAndReplaceDialog();
437      findAndReplaceDialog.ActivateSearch();
438    }
439
440    private void btnReplace_Click(object sender, EventArgs e) {
441      CreateFindAndReplaceDialog();
442      findAndReplaceDialog.ActivateReplace();
443    }
444  }
445}
Note: See TracBrowser for help on using the repository browser.