Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10706 was 10706, checked in by sbreuer, 10 years ago
  • start with search at the beginning when reached the end
File size: 14.7 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.MainForm;
29
30namespace HeuristicLab.DataPreprocessing.Views {
31  [View("Data Grid Content View")]
32  [Content(typeof(IDataGridContent), true)]
33  public partial class DataGridContentView : CopyOfStringConvertibleMatrixView {
34
35    private bool notOwnEvent = true;
36    private FindAndReplaceDialog findAndReplaceDialog;
37    private IFindPreprocessingItemsIterator searchIterator;
38    private string currentSearchText;
39    private Tuple<int, int> currentCell;
40
41    public new IDataGridContent Content {
42      get { return (IDataGridContent)base.Content; }
43      set { base.Content = value; }
44    }
45
46    private IList<int> _highlightedRowIndices;
47    public IList<int> HighlightedRowIndices {
48      get { return _highlightedRowIndices; }
49      set {
50        _highlightedRowIndices = value;
51        Refresh();
52      }
53    }
54
55    private IDictionary<int, IList<int>> _highlightedCells;
56    public IDictionary<int, IList<int>> HightlightedCells {
57      get { return _highlightedCells; }
58      set {
59        _highlightedCells = value;
60        Refresh();
61      }
62    }
63
64    public DataGridContentView() {
65      InitializeComponent();
66      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
67      dataGridView.CellPainting += new System.Windows.Forms.DataGridViewCellPaintingEventHandler(dataGridView_CellPainting);
68      dataGridView.KeyDown += dataGridView_KeyDown;
69      contextMenuCell.Items.Add(ShowHideColumns);
70      _highlightedCells = new Dictionary<int, IList<int>>();
71      _highlightedRowIndices = new List<int>();
72      currentCell = null;
73    }
74
75    protected override void OnContentChanged() {
76      base.OnContentChanged();
77    }
78
79    protected override void RegisterContentEvents() {
80      base.RegisterContentEvents();
81      Content.Changed += Content_Changed;
82    }
83
84    protected override void DeregisterContentEvents() {
85      base.DeregisterContentEvents();
86      Content.Changed -= Content_Changed;
87    }
88
89    void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
90      if (notOwnEvent) {
91        switch (e.Type) {
92          case DataPreprocessingChangedEventType.AddColumn:
93          case DataPreprocessingChangedEventType.AddRow:
94          case DataPreprocessingChangedEventType.DeleteColumn:
95          case DataPreprocessingChangedEventType.DeleteRow:
96          case DataPreprocessingChangedEventType.Any:
97            OnContentChanged();
98            break;
99          case DataPreprocessingChangedEventType.ChangeColumn:
100          case DataPreprocessingChangedEventType.ChangeItem:
101            dataGridView.Refresh();
102            break;
103        }
104
105      }
106    }
107
108    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
109      if (!dataGridView.ReadOnly) {
110        string errorMessage;
111        if (Content != null && !Content.DataGridLogic.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex)) {
112          e.Cancel = true;
113          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
114        }
115      }
116    }
117
118    protected override void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
119      triggersOwnEvent(() => base.dataGridView_CellParsing(sender, e));
120    }
121
122    protected override void PasteValuesToDataGridView() {
123      triggersOwnEvent(() => base.PasteValuesToDataGridView());
124    }
125
126    protected override void SetEnabledStateOfControls() {
127      base.SetEnabledStateOfControls();
128      rowsTextBox.ReadOnly = true;
129      columnsTextBox.ReadOnly = true;
130    }
131
132    private void btnApplySort_Click(object sender, System.EventArgs e) {
133      triggersOwnEvent(() => {
134        Content.PreprocessingDataManipulation.ReOrderToIndices(virtualRowIndices);
135        OnContentChanged();
136      });
137    }
138
139    private void triggersOwnEvent(Action action) {
140      notOwnEvent = false;
141      action();
142      notOwnEvent = true;
143    }
144
145    #region FindAndReplaceDialog
146
147    private void CreateFindAndReplaceDialog() {
148      findAndReplaceDialog = new FindAndReplaceDialog();
149      findAndReplaceDialog.Show(this);
150      findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
151      findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
152      findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
153      findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
154      findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
155    }
156
157    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
158      ResetHighlightedCells();
159    }
160
161    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
162      if (searchIterator != null && searchIterator.GetCurrent() != null)
163      {
164        Replace(TransformToDictionary(currentCell));
165      }
166    }
167
168    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
169      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
170    }
171
172    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
173      if (searchIterator == null || currentSearchText != findAndReplaceDialog.GetSearchText()) {
174        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
175        currentSearchText = findAndReplaceDialog.GetSearchText();
176      }
177     
178      bool moreOccurences = false;
179      do {
180        currentCell = searchIterator.GetCurrent();
181        moreOccurences = searchIterator.MoveNext();
182      } while (moreOccurences && (currentCell == null || !Content.GetValue(currentCell.Item2, currentCell.Item1).Equals(currentSearchText)));
183
184      if (currentCell != null) {
185        HightlightedCells = TransformToDictionary(currentCell);
186      } else {
187        ResetHighlightedCells();
188      }
189
190      if (!moreOccurences) {
191        searchIterator.Reset();
192        ResetHighlightedCells();
193      }
194    }
195
196    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
197      HightlightedCells = FindAll(findAndReplaceDialog.GetSearchText());
198    }
199
200    private IDictionary<int, IList<int>> FindAll(string match) {
201      var comparisonFilter = new Filter.ComparisonFilter(Content.FilterLogic.PreprocessingData, Core.ConstraintOperation.Equal, new StringValue(match), true);
202      var filters = new List<Filter.IFilter>() { comparisonFilter };
203      var foundCells = new Dictionary<int, IList<int>>();
204      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
205        comparisonFilter.ConstraintColumn = i;
206        bool[] filteredRows = Content.FilterLogic.Preview(filters);
207        foundCells[i] = filteredRows.Select((value, index) => new { Index = index, Value = value })
208          .Where(pair => pair.Value)
209          .Select(pair => pair.Index)
210          .ToList();
211      }
212      return foundCells;
213    }
214
215    private void Replace(IDictionary<int, IList<int>> cells) {
216      if (findAndReplaceDialog != null) {
217        switch (findAndReplaceDialog.GetReplaceAction()) {
218          case ReplaceAction.Value:
219            Content.PreprocessingDataManipulation.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
220            break;
221          case ReplaceAction.Average:
222            Content.PreprocessingDataManipulation.ReplaceIndicesByAverageValue(cells);
223            break;
224          case ReplaceAction.Median:
225            Content.PreprocessingDataManipulation.ReplaceIndicesByMedianValue(cells);
226            break;
227          case ReplaceAction.Random:
228            Content.PreprocessingDataManipulation.ReplaceIndicesByRandomValue(cells);
229            break;
230          case ReplaceAction.MostCommon:
231            Content.PreprocessingDataManipulation.ReplaceIndicesByMostCommonValue(cells);
232            break;
233          case ReplaceAction.Interpolation:
234            Content.PreprocessingDataManipulation.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
235            break;
236        }
237      }
238    }
239
240    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
241      var highlightCells = new Dictionary<int, IList<int>>();
242      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
243      return highlightCells;
244    }
245
246    private void ResetHighlightedCells() {
247      HightlightedCells = new Dictionary<int, IList<int>>();
248    }
249
250    #endregion FindAndReplaceDialog
251
252    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
253      if (Content == null) return;
254      if (e.Button == System.Windows.Forms.MouseButtons.Right) {
255        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
256          replaceValueToolStripMenuItem.Visible = false;
257          contextMenuCell.Show(MousePosition);
258        } else {
259          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
260            dataGridView.ClearSelection();
261            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
262          }
263          interpolationToolStripMenuItem.Enabled = !(e.RowIndex == 0 || e.RowIndex == Content.Rows);
264          var columnIndices = new HashSet<int>();
265          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
266            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
267          }
268          averageToolStripMenuItem.Enabled = medianToolStripMenuItem.Enabled = randomToolStripMenuItem.Enabled = !Content.DataGridLogic.AreAllStringColumns(columnIndices);
269          interpolationToolStripMenuItem.Enabled = interpolationToolStripMenuItem.Enabled && !Content.DataGridLogic.AreAllStringColumns(columnIndices);
270          replaceValueToolStripMenuItem.Visible = true;
271          contextMenuCell.Show(MousePosition);
272        }
273      }
274    }
275
276    protected void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
277      if (Content == null) return;
278      if (e.RowIndex < 0) return;
279      if (e.ColumnIndex < 0) return;
280      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
281      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
282      if (HighlightedRowIndices == null && HightlightedCells == null) return;
283
284      int rowIndex = virtualRowIndices[e.RowIndex];
285
286      Color backColor = e.CellStyle.BackColor;
287
288      if (HighlightedRowIndices.Contains(rowIndex) || HightlightedCells.ContainsKey(e.ColumnIndex) && HightlightedCells[e.ColumnIndex].Contains(e.RowIndex)) {
289        backColor = Color.Pink;
290      }
291
292      using (Brush backColorBrush = new SolidBrush(backColor)) {
293        Rectangle bounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
294        e.Graphics.FillRectangle(backColorBrush, bounds);
295      }
296     
297      using (Brush gridBrush = new SolidBrush(Color.LightGray)) {
298        Pen gridLinePen = new Pen(gridBrush);
299        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
300               e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
301               e.CellBounds.Bottom - 1);
302        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
303            e.CellBounds.Top, e.CellBounds.Right - 1,
304            e.CellBounds.Bottom);
305      }
306
307      e.PaintContent(e.CellBounds);
308      e.Handled = true;
309    }
310
311    void dataGridView_KeyDown(object sender, KeyEventArgs e) {
312      var selectedRows = dataGridView.SelectedRows;
313      if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
314        List<int> rows = new List<int>();
315        for (int i = 0; i < selectedRows.Count; ++i) {
316          rows.Add(selectedRows[i].Index);
317        }
318        triggersOwnEvent(() => {
319          Content.DataGridLogic.DeleteRow(rows);
320          OnContentChanged();
321        });
322      } else if (e.Control && e.KeyCode == Keys.F) {
323        CreateFindAndReplaceDialog();
324        findAndReplaceDialog.ActivateSearch();
325      } else if (e.Control && e.KeyCode == Keys.R) {
326        CreateFindAndReplaceDialog();
327        findAndReplaceDialog.ActivateReplace();
328      }
329    }
330
331    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
332      btnApplySort.Enabled = sortedColumns.Any();
333      return base.Sort(sortedColumns);
334    }
335
336    protected override void ClearSorting() {
337      btnApplySort.Enabled = false;
338      base.ClearSorting();
339    }
340
341    private IDictionary<int, IList<int>> GetSelectedCells() {
342      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
343      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
344        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
345        if (!selectedCells.ContainsKey(columnIndex)) {
346          selectedCells.Add(columnIndex, new List<int>());
347        }
348        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
349      }
350      return selectedCells;
351    }
352
353    private void ReplaceWithAverage_Click(object sender, EventArgs e) {
354      Content.PreprocessingDataManipulation.ReplaceIndicesByAverageValue(GetSelectedCells());
355    }
356
357    private void ReplaceWithMedian_Click(object sender, EventArgs e) {
358      Content.PreprocessingDataManipulation.ReplaceIndicesByMedianValue(GetSelectedCells());
359    }
360
361    private void ReplaceWithRandom_Click(object sender, EventArgs e) {
362      Content.PreprocessingDataManipulation.ReplaceIndicesByRandomValue(GetSelectedCells());
363    }
364
365    private void ReplaceWithMostCommon_Click(object sender, EventArgs e) {
366      Content.PreprocessingDataManipulation.ReplaceIndicesByMostCommonValue(GetSelectedCells());
367    }
368
369    private void ReplaceWithInterpolation_Click(object sender, EventArgs e) {
370      Content.PreprocessingDataManipulation.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
371    }
372  }
373}
Note: See TracBrowser for help on using the repository browser.