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

Last change on this file since 10785 was 10785, checked in by psteiner, 8 years ago

filter or combination
filter control: checkedlistview

File size: 17.0 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    }
85
86    protected override void OnContentChanged() {
87      base.OnContentChanged();
88      if (Content == null && findAndReplaceDialog != null) {
89        findAndReplaceDialog.Close();
90      }
91    }
92
93    protected override void RegisterContentEvents() {
94      base.RegisterContentEvents();
95      Content.Changed += Content_Changed;
96    }
97
98    protected override void DeregisterContentEvents() {
99      base.DeregisterContentEvents();
100      Content.Changed -= Content_Changed;
101    }
102
103    void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
104      if (notOwnEvent) {
105        switch (e.Type) {
106          case DataPreprocessingChangedEventType.AddColumn:
107          case DataPreprocessingChangedEventType.AddRow:
108          case DataPreprocessingChangedEventType.DeleteColumn:
109          case DataPreprocessingChangedEventType.DeleteRow:
110          case DataPreprocessingChangedEventType.Any:
111            OnContentChanged();
112            break;
113          case DataPreprocessingChangedEventType.ChangeColumn:
114          case DataPreprocessingChangedEventType.ChangeItem:
115            dataGridView.Refresh();
116            break;
117        }
118      }
119    }
120
121    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
122      if (!dataGridView.ReadOnly) {
123        string errorMessage;
124        if (Content != null && !Content.DataGridLogic.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex)) {
125          e.Cancel = true;
126          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
127        }
128      }
129    }
130
131    protected override void dataGridView_CellParsing(object sender, DataGridViewCellParsingEventArgs e) {
132      triggersOwnEvent(() => base.dataGridView_CellParsing(sender, e));
133    }
134
135    protected override void PasteValuesToDataGridView() {
136      triggersOwnEvent(() => base.PasteValuesToDataGridView());
137    }
138
139    protected override void SetEnabledStateOfControls() {
140      base.SetEnabledStateOfControls();
141      rowsTextBox.ReadOnly = true;
142      columnsTextBox.ReadOnly = true;
143    }
144
145    private void btnApplySort_Click(object sender, System.EventArgs e) {
146      triggersOwnEvent(() => {
147        Content.PreprocessingDataManipulation.ReOrderToIndices(virtualRowIndices);
148        OnContentChanged();
149      });
150    }
151
152    private void triggersOwnEvent(Action action) {
153      notOwnEvent = false;
154      action();
155      notOwnEvent = true;
156    }
157
158    #region FindAndReplaceDialog
159
160    private void CreateFindAndReplaceDialog() {
161      findAndReplaceDialog = new SearchAndReplaceDialog();
162      findAndReplaceDialog.Show(this);
163      HightlightedCellsBackground = GetSelectedCells();
164      dataGridView.ClearSelection();
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    }
171
172    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
173      ResetHighlightedCells();
174      ResetHighlightedCellsBackground();
175    }
176
177    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
178      if (searchIterator != null && searchIterator.GetCurrent() != null) {
179        Replace(TransformToDictionary(currentCell));
180      }
181    }
182
183    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
184      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
185    }
186
187    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
188      if (searchIterator == null || currentSearchText != findAndReplaceDialog.GetSearchText()) {
189        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
190        currentSearchText = findAndReplaceDialog.GetSearchText();
191      }
192
193      bool moreOccurences = false;
194      do {
195        currentCell = searchIterator.GetCurrent();
196        moreOccurences = searchIterator.MoveNext();
197      } while (moreOccurences && (currentCell == null || !Content.GetValue(currentCell.Item2, currentCell.Item1).Equals(currentSearchText)));
198
199      if (currentCell != null) {
200        HightlightedCells = TransformToDictionary(currentCell);
201        dataGridView.FirstDisplayedCell = dataGridView[currentCell.Item1, currentCell.Item2];
202      } else {
203        ResetHighlightedCells();
204      }
205
206      if (!moreOccurences) {
207        searchIterator.Reset();
208      }
209    }
210
211    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
212      HightlightedCells = FindAll(findAndReplaceDialog.GetSearchText());
213    }
214
215    private IDictionary<int, IList<int>> FindAll(string match) {
216      bool searchInSelection = HightlightedCellsBackground.Values.Sum(list => list.Count) > 1;
217      var comparisonFilter = new ComparisonFilter(Content.FilterLogic.PreprocessingData, Core.ConstraintOperation.Equal, new StringValue(match), true);
218      var filters = new List<Filter.IFilter>() { comparisonFilter };
219      var foundCells = new Dictionary<int, IList<int>>();
220      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
221        comparisonFilter.ConstraintColumn = i;
222        bool[] filteredRows = Content.FilterLogic.Preview(filters, true);
223        foundCells[i] = filteredRows.Select((value, index) => new { Index = index, Value = value })
224          .Where(pair => pair.Value)
225          .Select(pair => pair.Index)
226          .ToList();
227        IList<int> selectedList;
228        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
229          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
230        } else if (searchInSelection) {
231          foundCells[i].Clear();
232        }
233      }
234      return foundCells;
235    }
236
237    private void Replace(IDictionary<int, IList<int>> cells) {
238      if (findAndReplaceDialog != null) {
239        switch (findAndReplaceDialog.GetReplaceAction()) {
240          case ReplaceAction.Value:
241            Content.PreprocessingDataManipulation.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
242            break;
243          case ReplaceAction.Average:
244            Content.PreprocessingDataManipulation.ReplaceIndicesByAverageValue(cells);
245            break;
246          case ReplaceAction.Median:
247            Content.PreprocessingDataManipulation.ReplaceIndicesByMedianValue(cells);
248            break;
249          case ReplaceAction.Random:
250            Content.PreprocessingDataManipulation.ReplaceIndicesByRandomValue(cells);
251            break;
252          case ReplaceAction.MostCommon:
253            Content.PreprocessingDataManipulation.ReplaceIndicesByMostCommonValue(cells);
254            break;
255          case ReplaceAction.Interpolation:
256            Content.PreprocessingDataManipulation.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
257            break;
258        }
259      }
260    }
261
262    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
263      var highlightCells = new Dictionary<int, IList<int>>();
264      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
265      return highlightCells;
266    }
267
268    private void ResetHighlightedCells() {
269      HightlightedCells = new Dictionary<int, IList<int>>();
270    }
271
272    private void ResetHighlightedCellsBackground() {
273      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
274    }
275
276    #endregion FindAndReplaceDialog
277
278    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
279      if (Content == null) return;
280      if (e.Button == System.Windows.Forms.MouseButtons.Right) {
281        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
282          replaceValueOverColumnToolStripMenuItem.Visible = false;
283          contextMenuCell.Show(MousePosition);
284        } else {
285          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
286            dataGridView.ClearSelection();
287            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
288          }
289          interpolationToolStripMenuItem_Column.Enabled = !(e.RowIndex == 0 || e.RowIndex == Content.Rows);
290          var columnIndices = new HashSet<int>();
291          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
292            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
293          }
294          averageToolStripMenuItem_Column.Enabled = medianToolStripMenuItem_Column.Enabled = randomToolStripMenuItem_Column.Enabled = !Content.DataGridLogic.AreAllStringColumns(columnIndices);
295          interpolationToolStripMenuItem_Column.Enabled = interpolationToolStripMenuItem_Column.Enabled && !Content.DataGridLogic.AreAllStringColumns(columnIndices);
296          replaceValueOverColumnToolStripMenuItem.Visible = true;
297          contextMenuCell.Show(MousePosition);
298        }
299      }
300    }
301
302    protected void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
303      if (Content == null) return;
304      if (e.RowIndex < 0) return;
305      if (e.ColumnIndex < 0) return;
306      if (e.State.HasFlag(DataGridViewElementStates.Selected)) return;
307      if (!e.PaintParts.HasFlag(DataGridViewPaintParts.Background)) return;
308      if (HighlightedRowIndices == null && HightlightedCells == null) return;
309
310      int rowIndex = virtualRowIndices[e.RowIndex];
311
312      Color backColor = e.CellStyle.BackColor;
313
314      if (HightlightedCellsBackground.ContainsKey(e.ColumnIndex) && HightlightedCellsBackground[e.ColumnIndex].Contains(e.RowIndex)) {
315        backColor = Color.LightGray;
316      }
317      if (HighlightedRowIndices.Contains(rowIndex) || HightlightedCells.ContainsKey(e.ColumnIndex) && HightlightedCells[e.ColumnIndex].Contains(e.RowIndex)) {
318        backColor = Color.LightGreen;
319      }
320
321      using (Brush backColorBrush = new SolidBrush(backColor)) {
322        Rectangle bounds = new Rectangle(e.CellBounds.X, e.CellBounds.Y, e.CellBounds.Width, e.CellBounds.Height);
323        e.Graphics.FillRectangle(backColorBrush, bounds);
324      }
325
326      using (Brush gridBrush = new SolidBrush(Color.LightGray)) {
327        Pen gridLinePen = new Pen(gridBrush);
328        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
329               e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
330               e.CellBounds.Bottom - 1);
331        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
332            e.CellBounds.Top, e.CellBounds.Right - 1,
333            e.CellBounds.Bottom);
334      }
335
336      e.PaintContent(e.CellBounds);
337      e.Handled = true;
338    }
339
340    void dataGridView_KeyDown(object sender, KeyEventArgs e) {
341      var selectedRows = dataGridView.SelectedRows;
342      if (e.KeyCode == Keys.Delete && selectedRows.Count > 0) {
343        List<int> rows = new List<int>();
344        for (int i = 0; i < selectedRows.Count; ++i) {
345          rows.Add(selectedRows[i].Index);
346        }
347        triggersOwnEvent(() => {
348          Content.DataGridLogic.DeleteRow(rows);
349          OnContentChanged();
350        });
351      } else if (e.Control && e.KeyCode == Keys.F) {
352        CreateFindAndReplaceDialog();
353        findAndReplaceDialog.ActivateSearch();
354      } else if (e.Control && e.KeyCode == Keys.R) {
355        CreateFindAndReplaceDialog();
356        findAndReplaceDialog.ActivateReplace();
357      }
358    }
359
360    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
361      btnApplySort.Enabled = sortedColumns.Any();
362      return base.Sort(sortedColumns);
363    }
364
365    protected override void ClearSorting() {
366      btnApplySort.Enabled = false;
367      base.ClearSorting();
368    }
369
370    private IDictionary<int, IList<int>> GetSelectedCells() {
371      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
372      for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
373        var columnIndex = dataGridView.SelectedCells[i].ColumnIndex;
374        if (!selectedCells.ContainsKey(columnIndex)) {
375          selectedCells.Add(columnIndex, new List<int>());
376        }
377        selectedCells[columnIndex].Add(dataGridView.SelectedCells[i].RowIndex);
378      }
379      return selectedCells;
380    }
381
382    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
383      Content.PreprocessingDataManipulation.ReplaceIndicesByAverageValue(GetSelectedCells());
384    }
385
386    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
387      Content.PreprocessingDataManipulation.ReplaceIndicesByMedianValue(GetSelectedCells());
388    }
389
390    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
391      Content.PreprocessingDataManipulation.ReplaceIndicesByRandomValue(GetSelectedCells());
392    }
393
394    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
395      Content.PreprocessingDataManipulation.ReplaceIndicesByMostCommonValue(GetSelectedCells());
396    }
397
398    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
399      Content.PreprocessingDataManipulation.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
400    }
401
402    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
403    }
404
405    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
406    }
407
408    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
409    }
410
411    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
412    }
413
414    private void ReplaceWithInterpolation_Selection_Click(object sender, EventArgs e) {
415    }
416
417    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
418    }
419
420    private void btnSearch_Click(object sender, EventArgs e) {
421      CreateFindAndReplaceDialog();
422      findAndReplaceDialog.ActivateSearch();
423    }
424
425    private void btnReplace_Click(object sender, EventArgs e) {
426      CreateFindAndReplaceDialog();
427      findAndReplaceDialog.ActivateReplace();
428    }
429  }
430}
Note: See TracBrowser for help on using the repository browser.