Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10876 was 10876, checked in by rstoll, 9 years ago
  • Do not open Search and Replace twice
  • SelectionChanged event caused a NullPointer fixed
File size: 20.2 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 bool isSearching = false;
38    private SearchAndReplaceDialog findAndReplaceDialog;
39    private IFindPreprocessingItemsIterator searchIterator;
40    private string currentSearchText;
41    private ComparisonOperation currentComparisonOperation;
42    private Tuple<int, int> currentCell;
43
44    public new IDataGridContent Content {
45      get { return (IDataGridContent)base.Content; }
46      set { base.Content = value; }
47    }
48
49    private IList<int> _highlightedRowIndices;
50    public IList<int> HighlightedRowIndices {
51      get { return _highlightedRowIndices; }
52      set {
53        _highlightedRowIndices = value;
54        Refresh();
55      }
56    }
57
58    private IDictionary<int, IList<int>> _highlightedCellsBackground;
59    public IDictionary<int, IList<int>> HightlightedCellsBackground {
60      get { return _highlightedCellsBackground; }
61      set {
62        _highlightedCellsBackground = value;
63        Refresh();
64      }
65    }
66
67    public DataGridContentView() {
68      InitializeComponent();
69      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
70      dataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(dataGridView_CellPainting);
71      dataGridView.KeyDown += dataGridView_KeyDown;
72      contextMenuCell.Items.Add(ShowHideColumns);
73      _highlightedRowIndices = new List<int>();
74      _highlightedCellsBackground = new Dictionary<int, IList<int>>();
75      currentCell = null;
76      DataGridView.SelectionChanged += DataGridView_SelectionChanged;
77    }
78
79    void DataGridView_SelectionChanged(object sender, EventArgs e) {
80      if (!isSearching && Content != null) {
81        Content.DataGridLogic.SetSelection(GetSelectedCells());
82      }
83    }
84
85    protected override void OnContentChanged() {
86      base.OnContentChanged();
87      if (Content == null && findAndReplaceDialog != null) {
88        findAndReplaceDialog.Close();
89      }
90    }
91
92    protected override void RegisterContentEvents() {
93      base.RegisterContentEvents();
94      Content.Changed += Content_Changed;
95    }
96
97    protected override void DeregisterContentEvents() {
98      base.DeregisterContentEvents();
99      Content.Changed -= Content_Changed;
100    }
101
102    void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
103      if (notOwnEvent) {
104        switch (e.Type) {
105          case DataPreprocessingChangedEventType.ChangeColumn:
106          case DataPreprocessingChangedEventType.ChangeItem:
107            dataGridView.Refresh();
108            break;
109          default:
110            OnContentChanged();
111            break;
112        }
113      }
114      searchIterator = null;
115    }
116
117    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
118      if (!dataGridView.ReadOnly) {
119        string errorMessage;
120        if (Content != null && !Content.DataGridLogic.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex)) {
121          e.Cancel = true;
122          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
123        }
124      }
125    }
126
127    protected override void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
128      triggersOwnEvent(() => base.dataGridView_CellParsing(sender, e));
129    }
130
131    protected override void PasteValuesToDataGridView() {
132      triggersOwnEvent(() => base.PasteValuesToDataGridView());
133    }
134
135    protected override void SetEnabledStateOfControls() {
136      base.SetEnabledStateOfControls();
137      rowsTextBox.ReadOnly = true;
138      columnsTextBox.ReadOnly = true;
139    }
140
141    private void btnApplySort_Click(object sender, System.EventArgs e) {
142      triggersOwnEvent(() => {
143        Content.ManipulationLogic.ReOrderToIndices(virtualRowIndices);
144        OnContentChanged();
145      });
146    }
147
148    private void triggersOwnEvent(Action action) {
149      notOwnEvent = false;
150      action();
151      notOwnEvent = true;
152    }
153
154    #region FindAndReplaceDialog
155
156    private void CreateFindAndReplaceDialog() {
157      if (findAndReplaceDialog == null || findAndReplaceDialog.IsDisposed) {
158        findAndReplaceDialog = new SearchAndReplaceDialog();
159        findAndReplaceDialog.Show(this);
160        if (AreMultipleCellsSelected()) {
161          ResetHighlightedCellsBackground();
162          HightlightedCellsBackground = GetSelectedCells();
163          dataGridView.ClearSelection();
164        }
165        findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
166        findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
167        findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
168        findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
169        findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
170        searchIterator = null;
171        DataGridView.SelectionChanged += DataGridView_SelectionChanged_FindAndReplace;
172      }
173    }
174
175    void DataGridView_SelectionChanged_FindAndReplace(object sender, EventArgs e) {
176      if (Content != null) {
177        if (!isSearching && AreMultipleCellsSelected()) {
178          ResetHighlightedCellsBackground();
179          HightlightedCellsBackground = GetSelectedCells();
180          searchIterator = null;
181        }
182      }
183    }
184
185    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
186      ResetHighlightedCellsBackground();
187      searchIterator = null;
188      DataGridView.SelectionChanged -= DataGridView_SelectionChanged_FindAndReplace;
189    }
190
191    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
192      if (searchIterator != null && searchIterator.GetCurrent() != null) {
193        Replace(TransformToDictionary(currentCell));
194      }
195    }
196
197    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
198      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
199    }
200
201    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
202      if (searchIterator == null ||
203        currentSearchText != findAndReplaceDialog.GetSearchText() ||
204        currentComparisonOperation != findAndReplaceDialog.GetComparisonOperation()) {
205        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
206        currentSearchText = findAndReplaceDialog.GetSearchText();
207        currentComparisonOperation = findAndReplaceDialog.GetComparisonOperation();
208      }
209
210      if (IsOneCellSelected()) {
211        var first = GetSelectedCells().First();
212        searchIterator.SetStartCell(first.Key, first.Value[0]);
213      }
214
215      bool moreOccurences = false;
216      currentCell = searchIterator.GetCurrent();
217      moreOccurences = searchIterator.MoveNext();
218      if (IsOneCellSelected() && currentCell != null) {
219        var first = GetSelectedCells().First();
220        if (currentCell.Item1 == first.Key && currentCell.Item2 == first.Value[0]) {
221          if (!moreOccurences) {
222            searchIterator.Reset();
223          }
224          currentCell = searchIterator.GetCurrent();
225          moreOccurences = searchIterator.MoveNext();
226          if (!moreOccurences) {
227            searchIterator.Reset();
228          }
229        }
230      }
231
232      dataGridView.ClearSelection();
233
234      if (currentCell != null) {
235        dataGridView[currentCell.Item1, currentCell.Item2].Selected = true;
236      }
237    }
238
239    private bool AreMultipleCellsSelected() {
240      return GetSelectedCellCount() > 1;
241    }
242
243    private bool IsOneCellSelected() {
244      return GetSelectedCellCount() == 1;
245    }
246
247    private int GetSelectedCellCount() {
248      int count = 0;
249      foreach (var column in GetSelectedCells()) {
250        count += column.Value.Count();
251      }
252      return count;
253    }
254
255    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
256      dataGridView.ClearSelection();
257      isSearching = true;
258      foreach (var column in FindAll(findAndReplaceDialog.GetSearchText())) {
259        foreach (var cell in column.Value) {
260          dataGridView[column.Key, cell].Selected = true;
261        }
262      }
263      isSearching = false;
264      DataGridView_SelectionChanged(null, null);
265    }
266
267    private Core.ConstraintOperation GetConstraintOperation(ComparisonOperation comparisonOperation) {
268      Core.ConstraintOperation constraintOperation = Core.ConstraintOperation.Equal;
269      switch (comparisonOperation) {
270        case ComparisonOperation.Equal:
271          constraintOperation = Core.ConstraintOperation.Equal;
272          break;
273        case ComparisonOperation.Greater:
274          constraintOperation = Core.ConstraintOperation.Greater;
275          break;
276        case ComparisonOperation.GreaterOrEqual:
277          constraintOperation = Core.ConstraintOperation.GreaterOrEqual;
278          break;
279        case ComparisonOperation.Less:
280          constraintOperation = Core.ConstraintOperation.Less;
281          break;
282        case ComparisonOperation.LessOrEqual:
283          constraintOperation = Core.ConstraintOperation.LessOrEqual;
284          break;
285        case ComparisonOperation.NotEqual:
286          constraintOperation = Core.ConstraintOperation.NotEqual;
287          break;
288      }
289      return constraintOperation;
290    }
291
292    private IDictionary<int, IList<int>> FindAll(string match) {
293      bool searchInSelection = HightlightedCellsBackground.Values.Sum(list => list.Count) > 1;
294      ComparisonOperation comparisonOperation = findAndReplaceDialog.GetComparisonOperation();
295      var comparisonFilter = new ComparisonFilter(Content.FilterLogic.PreprocessingData, GetConstraintOperation(comparisonOperation), new StringValue(match), true);
296      var filters = new List<Filter.IFilter>() { comparisonFilter };
297      var foundCells = new Dictionary<int, IList<int>>();
298      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
299        comparisonFilter.ConstraintColumn = i;
300        bool[] filteredRows = Content.FilterLogic.GetFilterResult(filters, true);
301        var foundIndices = new List<int>();
302        for (int idx = 0; idx < filteredRows.Length; ++idx) {
303          var notFilteredThusFound = !filteredRows[idx];
304          if (notFilteredThusFound) {
305            foundIndices.Add(idx);
306          }
307        }
308        foundCells[i] = foundIndices;
309        IList<int> selectedList;
310        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
311          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
312        } else if (searchInSelection) {
313          foundCells[i].Clear();
314        }
315      }
316      return foundCells;
317    }
318
319    private void Replace(IDictionary<int, IList<int>> cells) {
320      if (findAndReplaceDialog != null) {
321        switch (findAndReplaceDialog.GetReplaceAction()) {
322          case ReplaceAction.Value:
323            Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
324            break;
325          case ReplaceAction.Average:
326            Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
327            break;
328          case ReplaceAction.Median:
329            Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
330            break;
331          case ReplaceAction.Random:
332            Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
333            break;
334          case ReplaceAction.MostCommon:
335            Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
336            break;
337          case ReplaceAction.Interpolation:
338            Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
339            break;
340        }
341      }
342    }
343
344    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
345      var highlightCells = new Dictionary<int, IList<int>>();
346      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
347      return highlightCells;
348    }
349
350    private void ResetHighlightedCellsBackground() {
351      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
352    }
353
354    #endregion FindAndReplaceDialog
355
356    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
357      if (Content == null) return;
358      if (e.Button == System.Windows.Forms.MouseButtons.Right) {
359        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
360          replaceValueOverColumnToolStripMenuItem.Visible = false;
361          contextMenuCell.Show(MousePosition);
362        } else {
363          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
364            dataGridView.ClearSelection();
365            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
366          }
367
368          var columnIndices = new HashSet<int>();
369          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
370            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
371          }
372
373          replaceValueOverSelectionToolStripMenuItem.Enabled = AreMultipleCellsSelected();
374
375          averageToolStripMenuItem_Column.Enabled =
376            averageToolStripMenuItem_Selection.Enabled =
377            medianToolStripMenuItem_Column.Enabled =
378            medianToolStripMenuItem_Selection.Enabled =
379            randomToolStripMenuItem_Column.Enabled =
380            randomToolStripMenuItem_Selection.Enabled = !Content.DataGridLogic.AreAllStringColumns(columnIndices);
381
382          smoothingToolStripMenuItem_Column.Enabled =
383            interpolationToolStripMenuItem_Column.Enabled = !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, 0])
384            && !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, Content.Rows - 1])
385            && !Content.DataGridLogic.AreAllStringColumns(columnIndices);
386
387          replaceValueOverColumnToolStripMenuItem.Visible = true;
388          contextMenuCell.Show(MousePosition);
389        }
390      }
391    }
392
393    protected void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
394      if (Content == null) return;
395      if (e.RowIndex < 0) return;
396      if (e.ColumnIndex < 0) return;
397      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
398      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
399      if (HighlightedRowIndices == null) return;
400
401      int rowIndex = virtualRowIndices[e.RowIndex];
402
403      Color backColor = e.CellStyle.BackColor;
404
405      if (HightlightedCellsBackground.ContainsKey(e.ColumnIndex) && HightlightedCellsBackground[e.ColumnIndex].Contains(e.RowIndex)) {
406        backColor = Color.LightGray;
407      }
408
409      using (Brush backColorBrush = new SolidBrush(backColor)) {
410        Rectangle bounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
411        e.Graphics.FillRectangle(backColorBrush, bounds);
412      }
413
414      using (Brush gridBrush = new SolidBrush(Color.LightGray)) {
415        Pen gridLinePen = new Pen(gridBrush);
416        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
417               e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
418               e.CellBounds.Bottom - 1);
419        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
420            e.CellBounds.Top, e.CellBounds.Right - 1,
421            e.CellBounds.Bottom);
422      }
423
424      e.PaintContent(e.CellBounds);
425      e.Handled = true;
426    }
427
428    void dataGridView_KeyDown(object sender, KeyEventArgs e) {
429      var selectedRows = dataGridView.SelectedRows;
430      if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
431        List<int> rows = new List<int>();
432        for (int i = 0; i < selectedRows.Count; ++i) {
433          rows.Add(selectedRows[i].Index);
434        }
435        triggersOwnEvent(() => {
436          Content.DataGridLogic.DeleteRow(rows);
437          OnContentChanged();
438        });
439      } else if (e.Control && e.KeyCode == Keys.F) {
440        CreateFindAndReplaceDialog();
441        findAndReplaceDialog.ActivateSearch();
442      } else if (e.Control && e.KeyCode == Keys.R) {
443        CreateFindAndReplaceDialog();
444        findAndReplaceDialog.ActivateReplace();
445      }
446    }
447
448    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
449      btnApplySort.Enabled = sortedColumns.Any();
450      return base.Sort(sortedColumns);
451    }
452
453    protected override void ClearSorting() {
454      btnApplySort.Enabled = false;
455      base.ClearSorting();
456    }
457
458    private IDictionary<int, IList<int>> GetSelectedCells() {
459      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
460      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
461        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
462        if (!selectedCells.ContainsKey(columnIndex)) {
463          selectedCells.Add(columnIndex, new List<int>());
464        }
465        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
466      }
467      return selectedCells;
468    }
469
470    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
471      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
472    }
473    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
474      Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
475    }
476
477    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
478      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
479    }
480    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
481      Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
482    }
483
484    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
485      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
486    }
487    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
488      Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
489    }
490
491    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
492      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
493    }
494    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
495      Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
496    }
497
498    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
499      Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
500    }
501
502    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
503      Content.ManipulationLogic.ReplaceIndicesBySmoothing(GetSelectedCells());
504    }
505
506    private void btnSearch_Click(object sender, EventArgs e) {
507      CreateFindAndReplaceDialog();
508      findAndReplaceDialog.ActivateSearch();
509    }
510
511    private void btnReplace_Click(object sender, EventArgs e) {
512      CreateFindAndReplaceDialog();
513      findAndReplaceDialog.ActivateReplace();
514    }
515  }
516}
Note: See TracBrowser for help on using the repository browser.