Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.DataPreprocessing.Views/3.4/DataGridContentView.cs @ 15016

Last change on this file since 15016 was 14797, checked in by mkommend, 8 years ago

#2714: Merged r14443 and r14548 into stable.

File size: 27.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Data;
27using HeuristicLab.Data.Views;
28using HeuristicLab.DataPreprocessing.Filter;
29using HeuristicLab.MainForm;
30
31namespace HeuristicLab.DataPreprocessing.Views {
32  [View("Data Grid Content View")]
33  [Content(typeof(DataGridContent), true)]
34  public partial class DataGridContentView : StringConvertibleMatrixView {
35
36    private bool isSearching = false;
37    private bool updateOnMouseUp = 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 DataGridContent Content {
45      get { return (DataGridContent)base.Content; }
46      set { base.Content = value; }
47    }
48
49    private IDictionary<int, IList<int>> _highlightedCellsBackground;
50    public IDictionary<int, IList<int>> HightlightedCellsBackground {
51      get { return _highlightedCellsBackground; }
52      set {
53        _highlightedCellsBackground = value;
54        Refresh();
55      }
56    }
57
58    public DataGridContentView() {
59      InitializeComponent();
60      dataGridView.MouseDown += dataGridView_MouseDown;
61      dataGridView.CellMouseClick += dataGridView_CellMouseClick;
62      dataGridView.RowHeaderMouseClick += dataGridView_RowHeaderMouseClick;
63      dataGridView.MouseUp += dataGridView_MouseUp;
64      contextMenuCell.Items.Add(ShowHideColumns);
65      _highlightedCellsBackground = new Dictionary<int, IList<int>>();
66      currentCell = null;
67    }
68
69    protected override void OnContentChanged() {
70      List<KeyValuePair<int, SortOrder>> order = new List<KeyValuePair<int, SortOrder>>(base.sortedColumnIndices);
71      base.OnContentChanged();
72
73      DataGridView.RowHeadersWidth = 70;
74
75      if (Content == null && findAndReplaceDialog != null) {
76        findAndReplaceDialog.Close();
77      }
78
79      if (Content != null) {
80        base.sortedColumnIndices = order;
81        base.Sort();
82      }
83
84    }
85
86    protected override void RegisterContentEvents() {
87      base.RegisterContentEvents();
88      Content.Changed += Content_Changed;
89      Content.FilterLogic.FilterChanged += FilterLogic_FilterChanged;
90    }
91
92    protected override void DeregisterContentEvents() {
93      base.DeregisterContentEvents();
94      Content.Changed -= Content_Changed;
95      Content.FilterLogic.FilterChanged -= FilterLogic_FilterChanged;
96    }
97
98    private void FilterLogic_FilterChanged(object sender, EventArgs e) {
99      OnContentChanged();
100      searchIterator = null;
101      if (findAndReplaceDialog != null && !findAndReplaceDialog.IsDisposed) {
102        if (Content.FilterLogic.IsFiltered) {
103          findAndReplaceDialog.DisableReplace();
104        } else {
105          findAndReplaceDialog.EnableReplace();
106        }
107      }
108      btnReplace.Enabled = !Content.FilterLogic.IsFiltered;
109    }
110
111    private void Content_Changed(object sender, DataPreprocessingChangedEventArgs e) {
112      OnContentChanged();
113      searchIterator = null;
114    }
115
116    protected override void dataGridView_SelectionChanged(object sender, EventArgs e) {
117      base.dataGridView_SelectionChanged(sender, e);
118      if (Content != null && dataGridView.RowCount != 0 && dataGridView.ColumnCount != 0)
119        Content.Selection = GetSelectedCells();
120    }
121
122    //couldn't use base.dataGridView_CellValidating as the values have to be validated per column individually
123    protected override void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
124      if (dataGridView.ReadOnly) return;
125      if (Content == null) return;
126      if (Content.Rows == 0 || Content.Columns == 0) return;
127
128      string errorMessage;
129      if (!String.IsNullOrEmpty(e.FormattedValue.ToString())) {
130        if (dataGridView.IsCurrentCellInEditMode && Content.FilterLogic.IsFiltered) {
131          errorMessage = "A filter is active, you cannot modify data. Press ESC to exit edit mode.";
132        } else {
133          Content.Validate(e.FormattedValue.ToString(), out errorMessage, e.ColumnIndex);
134        }
135
136        if (!String.IsNullOrEmpty(errorMessage)) {
137          e.Cancel = true;
138          dataGridView.Rows[e.RowIndex].ErrorText = errorMessage;
139        }
140
141      }
142    }
143
144
145    protected override void PasteValuesToDataGridView() {
146      string[,] values = SplitClipboardString(Clipboard.GetText());
147      if (values.Length == 0) return;
148      int rowIndex = 0;
149      int columnIndex = 0;
150      if (dataGridView.CurrentCell != null) {
151        rowIndex = dataGridView.CurrentCell.RowIndex;
152        columnIndex = dataGridView.CurrentCell.ColumnIndex;
153      }
154
155      bool containsHeader = false;
156      var firstRow = Enumerable.Range(0, values.GetLength(0)).Select(col => values[col, 0]).ToList();
157      if ((Content.Selection.Values.Sum(s => s.Count) == Content.Rows * Content.Columns)
158          || (rowIndex == 0 && columnIndex == 0 && Content.Rows <= values.GetLength(1) && Content.Columns <= values.GetLength(0))) {
159        // All is selected -or- top left selected and everything will be replaced
160        double temp;
161        containsHeader = !firstRow.All(string.IsNullOrEmpty) && firstRow.Any(r => !double.TryParse(r, out temp));
162        if (containsHeader)
163          rowIndex = columnIndex = 0;
164      }
165
166      int newRows = values.GetLength(1) + rowIndex - (containsHeader ? 1 : 0);
167      int newColumns = values.GetLength(0) + columnIndex;
168      if (Content.Rows < newRows) Content.Rows = newRows;
169      if (Content.Columns < newColumns) Content.Columns = newColumns;
170
171      ReplaceTransaction(() => {
172        Content.PreProcessingData.InTransaction(() => {
173          for (int row = containsHeader ? 1 : 0; row < values.GetLength(1); row++) {
174            for (int col = 0; col < values.GetLength(0); col++) {
175              Content.SetValue(values[col, row], row + rowIndex - (containsHeader ? 1 : 0), col + columnIndex);
176            }
177          }
178          if (containsHeader) {
179            for (int i = 0; i < firstRow.Count; i++)
180              if (string.IsNullOrWhiteSpace(firstRow[i]))
181                firstRow[i] = string.Format("<{0}>", i);
182            Content.PreProcessingData.RenameColumns(firstRow);
183          }
184        });
185      });
186
187      ClearSorting();
188    }
189
190    protected override void SetEnabledStateOfControls() {
191      base.SetEnabledStateOfControls();
192      rowsTextBox.ReadOnly = true;
193      columnsTextBox.ReadOnly = true;
194    }
195
196    protected override int[] Sort(IEnumerable<KeyValuePair<int, SortOrder>> sortedColumns) {
197      btnApplySort.Enabled = sortedColumns.Any();
198      return base.Sort(sortedColumns);
199    }
200
201    protected override void ClearSorting() {
202      btnApplySort.Enabled = false;
203      base.ClearSorting();
204    }
205
206    //Necessary so that dataGridView.SelectedRows and SelectedColumns are populated correctly
207    //further information: https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.selectedcolumns.aspx
208    private void dataGridView_MouseDown(object sender, MouseEventArgs e) {
209      var hitTestInfo = dataGridView.HitTest(e.X, e.Y);
210      // row header click
211      if (hitTestInfo.ColumnIndex == -1 && hitTestInfo.RowIndex >= 0) {
212        if (dataGridView.SelectionMode != DataGridViewSelectionMode.RowHeaderSelect) {
213          dataGridView.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;
214        }
215      }
216      // column header click
217      if (hitTestInfo.RowIndex == -1 && hitTestInfo.ColumnIndex >= 0) {
218        if (dataGridView.SelectionMode != DataGridViewSelectionMode.ColumnHeaderSelect) {
219          dataGridView.SelectionMode = DataGridViewSelectionMode.ColumnHeaderSelect;
220        }
221      }
222    }
223
224    protected override void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
225      if (Content == null) return;
226
227      if (e.Button == MouseButtons.Middle) {
228        int newIndex = e.ColumnIndex >= 0 ? e.ColumnIndex : 0;
229        Content.PreProcessingData.InsertColumn<double>(newIndex.ToString(), newIndex);
230      } else if (e.Button == MouseButtons.Right && Content.SortableView) {
231        SortColumn(e.ColumnIndex);
232      }
233
234      searchIterator = null;
235    }
236    private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
237      if (Content != null) {
238        if (e.Button == MouseButtons.Middle) {
239          int newIndex = e.RowIndex >= 0 ? e.RowIndex : 0;
240          Content.PreProcessingData.InsertRow(newIndex);
241        }
242      }
243    }
244
245    private void dataGridView_MouseUp(object sender, MouseEventArgs e) {
246      if (!updateOnMouseUp)
247        return;
248
249      updateOnMouseUp = false;
250      dataGridView_SelectionChanged(sender, e);
251    }
252
253    private void btnApplySort_Click(object sender, System.EventArgs e) {
254      Content.ManipulationLogic.ReOrderToIndices(virtualRowIndices);
255      OnContentChanged();
256    }
257
258    #region FindAndReplaceDialog
259
260    private void CreateFindAndReplaceDialog() {
261      if (findAndReplaceDialog == null || findAndReplaceDialog.IsDisposed) {
262        findAndReplaceDialog = new SearchAndReplaceDialog();
263        findAndReplaceDialog.Show(this);
264        if (AreMultipleCellsSelected()) {
265          ResetHighlightedCellsBackground();
266          HightlightedCellsBackground = GetSelectedCells();
267          dataGridView.ClearSelection();
268        }
269        findAndReplaceDialog.FindAllEvent += findAndReplaceDialog_FindAllEvent;
270        findAndReplaceDialog.FindNextEvent += findAndReplaceDialog_FindNextEvent;
271        findAndReplaceDialog.ReplaceAllEvent += findAndReplaceDialog_ReplaceAllEvent;
272        findAndReplaceDialog.ReplaceNextEvent += findAndReplaceDialog_ReplaceEvent;
273        findAndReplaceDialog.FormClosing += findAndReplaceDialog_FormClosing;
274        searchIterator = null;
275        DataGridView.SelectionChanged += DataGridView_SelectionChanged_FindAndReplace;
276        if (Content.FilterLogic.IsFiltered) {
277          findAndReplaceDialog.DisableReplace();
278        }
279      }
280    }
281
282    private void DataGridView_SelectionChanged_FindAndReplace(object sender, EventArgs e) {
283      if (Content != null) {
284        if (!isSearching && AreMultipleCellsSelected()) {
285          ResetHighlightedCellsBackground();
286          HightlightedCellsBackground = GetSelectedCells();
287          searchIterator = null;
288        }
289      }
290    }
291
292    void findAndReplaceDialog_FormClosing(object sender, FormClosingEventArgs e) {
293      ResetHighlightedCellsBackground();
294      searchIterator = null;
295      DataGridView.SelectionChanged -= DataGridView_SelectionChanged_FindAndReplace;
296    }
297
298    void findAndReplaceDialog_ReplaceEvent(object sender, EventArgs e) {
299      if (searchIterator != null && searchIterator.GetCurrent() != null) {
300        Replace(TransformToDictionary(currentCell));
301      }
302    }
303
304    void findAndReplaceDialog_ReplaceAllEvent(object sender, EventArgs e) {
305      Replace(FindAll(findAndReplaceDialog.GetSearchText()));
306    }
307
308    void findAndReplaceDialog_FindNextEvent(object sender, EventArgs e) {
309      if (searchIterator == null
310        || currentSearchText != findAndReplaceDialog.GetSearchText()
311        || currentComparisonOperation != findAndReplaceDialog.GetComparisonOperation()) {
312
313        searchIterator = new FindPreprocessingItemsIterator(FindAll(findAndReplaceDialog.GetSearchText()));
314        currentSearchText = findAndReplaceDialog.GetSearchText();
315        currentComparisonOperation = findAndReplaceDialog.GetComparisonOperation();
316      }
317
318      if (IsOneCellSelected()) {
319        var first = GetSelectedCells().First();
320        searchIterator.SetStartCell(first.Key, first.Value[0]);
321      }
322
323      bool moreOccurences = false;
324      currentCell = searchIterator.GetCurrent();
325      moreOccurences = searchIterator.MoveNext();
326      if (IsOneCellSelected() && currentCell != null) {
327        var first = GetSelectedCells().First();
328        if (currentCell.Item1 == first.Key && currentCell.Item2 == first.Value[0]) {
329          if (!moreOccurences) {
330            searchIterator.Reset();
331          }
332          currentCell = searchIterator.GetCurrent();
333          moreOccurences = searchIterator.MoveNext();
334          if (!moreOccurences) {
335            searchIterator.Reset();
336          }
337        }
338      }
339
340      dataGridView.ClearSelection();
341
342      if (currentCell != null) {
343        dataGridView[currentCell.Item1, currentCell.Item2].Selected = true;
344        dataGridView.CurrentCell = dataGridView[currentCell.Item1, currentCell.Item2];
345      }
346    }
347
348    private bool AreMultipleCellsSelected() {
349      return GetSelectedCellCount() > 1;
350    }
351
352    private bool IsOneCellSelected() {
353      return GetSelectedCellCount() == 1;
354    }
355
356    private int GetSelectedCellCount() {
357      int count = 0;
358      foreach (var column in GetSelectedCells()) {
359        count += column.Value.Count();
360      }
361      return count;
362    }
363
364    void findAndReplaceDialog_FindAllEvent(object sender, EventArgs e) {
365      dataGridView.ClearSelection();
366      isSearching = true;
367      SuspendRepaint();
368      var selectedCells = FindAll(findAndReplaceDialog.GetSearchText());
369      foreach (var column in selectedCells) {
370        foreach (var cell in column.Value) {
371          dataGridView[column.Key, cell].Selected = true;
372        }
373      }
374      ResumeRepaint(true);
375      isSearching = false;
376      Content.Selection = selectedCells;
377      //update statistic in base
378      base.dataGridView_SelectionChanged(sender, e);
379    }
380
381    private Core.ConstraintOperation GetConstraintOperation(ComparisonOperation comparisonOperation) {
382      Core.ConstraintOperation constraintOperation = Core.ConstraintOperation.Equal;
383      switch (comparisonOperation) {
384        case ComparisonOperation.Equal:
385          constraintOperation = Core.ConstraintOperation.Equal;
386          break;
387        case ComparisonOperation.Greater:
388          constraintOperation = Core.ConstraintOperation.Greater;
389          break;
390        case ComparisonOperation.GreaterOrEqual:
391          constraintOperation = Core.ConstraintOperation.GreaterOrEqual;
392          break;
393        case ComparisonOperation.Less:
394          constraintOperation = Core.ConstraintOperation.Less;
395          break;
396        case ComparisonOperation.LessOrEqual:
397          constraintOperation = Core.ConstraintOperation.LessOrEqual;
398          break;
399        case ComparisonOperation.NotEqual:
400          constraintOperation = Core.ConstraintOperation.NotEqual;
401          break;
402      }
403      return constraintOperation;
404    }
405
406    private IDictionary<int, IList<int>> FindAll(string match) {
407      bool searchInSelection = HightlightedCellsBackground.Values.Sum(list => list.Count) > 1;
408      ComparisonOperation comparisonOperation = findAndReplaceDialog.GetComparisonOperation();
409      var foundCells = new Dictionary<int, IList<int>>();
410      for (int i = 0; i < Content.FilterLogic.PreprocessingData.Columns; i++) {
411        var filters = CreateFilters(match, comparisonOperation, i);
412
413        bool[] filteredRows = Content.FilterLogic.GetFilterResult(filters, true);
414        var foundIndices = new List<int>();
415        for (int idx = 0; idx < filteredRows.Length; ++idx) {
416          var notFilteredThusFound = !filteredRows[idx];
417          if (notFilteredThusFound) {
418            foundIndices.Add(idx);
419          }
420        }
421        foundCells[i] = foundIndices;
422        IList<int> selectedList;
423        if (searchInSelection && HightlightedCellsBackground.TryGetValue(i, out selectedList)) {
424          foundCells[i] = foundCells[i].Intersect(selectedList).ToList<int>();
425        } else if (searchInSelection) {
426          foundCells[i].Clear();
427        }
428      }
429      return MapToSorting(foundCells);
430    }
431
432    private List<IFilter> CreateFilters(string match, ComparisonOperation comparisonOperation, int columnIndex) {
433      IPreprocessingData preprocessingData = Content.FilterLogic.PreprocessingData;
434      IStringConvertibleValue value;
435      if (preprocessingData.VariableHasType<double>(columnIndex)) {
436        value = new DoubleValue();
437      } else if (preprocessingData.VariableHasType<String>(columnIndex)) {
438        value = new StringValue();
439      } else if (preprocessingData.VariableHasType<DateTime>(columnIndex)) {
440        value = new DateTimeValue();
441      } else {
442        throw new ArgumentException("unsupported type");
443      }
444      value.SetValue(match);
445      var comparisonFilter = new ComparisonFilter(preprocessingData, GetConstraintOperation(comparisonOperation), value, true);
446      comparisonFilter.ConstraintColumn = columnIndex;
447      return new List<Filter.IFilter>() { comparisonFilter };
448    }
449
450    private IDictionary<int, IList<int>> MapToSorting(Dictionary<int, IList<int>> foundCells) {
451      if (sortedColumnIndices.Count == 0) {
452        return foundCells;
453      } else {
454        var sortedFoundCells = new Dictionary<int, IList<int>>();
455
456        var indicesToVirtual = new Dictionary<int, int>();
457        for (int i = 0; i < virtualRowIndices.Length; ++i) {
458          indicesToVirtual.Add(virtualRowIndices[i], i);
459        }
460
461        foreach (var entry in foundCells) {
462          var cells = new List<int>();
463          foreach (var cell in entry.Value) {
464            cells.Add(indicesToVirtual[cell]);
465          }
466          cells.Sort();
467          sortedFoundCells.Add(entry.Key, cells);
468        }
469        return sortedFoundCells;
470      }
471    }
472
473    private void Replace(IDictionary<int, IList<int>> cells) {
474      if (findAndReplaceDialog != null) {
475        ReplaceTransaction(() => {
476          switch (findAndReplaceDialog.GetReplaceAction()) {
477            case ReplaceAction.Value:
478              Content.ManipulationLogic.ReplaceIndicesByValue(cells, findAndReplaceDialog.GetReplaceText());
479              break;
480            case ReplaceAction.Average:
481              Content.ManipulationLogic.ReplaceIndicesByAverageValue(cells, false);
482              break;
483            case ReplaceAction.Median:
484              Content.ManipulationLogic.ReplaceIndicesByMedianValue(cells, false);
485              break;
486            case ReplaceAction.Random:
487              Content.ManipulationLogic.ReplaceIndicesByRandomValue(cells, false);
488              break;
489            case ReplaceAction.MostCommon:
490              Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(cells, false);
491              break;
492            case ReplaceAction.Interpolation:
493              Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(cells);
494              break;
495          }
496        });
497      }
498    }
499
500    private IDictionary<int, IList<int>> TransformToDictionary(Tuple<int, int> tuple) {
501      var highlightCells = new Dictionary<int, IList<int>>();
502      highlightCells.Add(tuple.Item1, new List<int>() { tuple.Item2 });
503      return highlightCells;
504    }
505
506    private void ResetHighlightedCellsBackground() {
507      HightlightedCellsBackground = new Dictionary<int, IList<int>>();
508    }
509
510    #endregion FindAndReplaceDialog
511
512    private void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
513      if (Content == null) return;
514      if (e.Button == MouseButtons.Right && !(e.ColumnIndex != -1 && e.RowIndex == -1)) {
515        if (e.ColumnIndex == -1 || e.RowIndex == -1) {
516          replaceValueOverColumnToolStripMenuItem.Visible = false;
517          contextMenuCell.Show(MousePosition);
518        } else {
519          if (!dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, e.RowIndex])) {
520            dataGridView.ClearSelection();
521            dataGridView[e.ColumnIndex, e.RowIndex].Selected = true;
522          }
523
524          var columnIndices = new HashSet<int>();
525          for (int i = 0; i < dataGridView.SelectedCells.Count; i++) {
526            columnIndices.Add(dataGridView.SelectedCells[i].ColumnIndex);
527          }
528
529          replaceValueOverSelectionToolStripMenuItem.Enabled = AreMultipleCellsSelected();
530
531          averageToolStripMenuItem_Column.Enabled =
532            averageToolStripMenuItem_Selection.Enabled =
533            medianToolStripMenuItem_Column.Enabled =
534            medianToolStripMenuItem_Selection.Enabled =
535            randomToolStripMenuItem_Column.Enabled =
536            randomToolStripMenuItem_Selection.Enabled = !Content.PreProcessingData.AreAllStringColumns(columnIndices);
537
538          smoothingToolStripMenuItem_Column.Enabled =
539            interpolationToolStripMenuItem_Column.Enabled = !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, 0])
540            && !dataGridView.SelectedCells.Contains(dataGridView[e.ColumnIndex, Content.Rows - 1])
541            && !Content.PreProcessingData.AreAllStringColumns(columnIndices);
542
543          replaceValueOverColumnToolStripMenuItem.Visible = true;
544          contextMenuCell.Show(MousePosition);
545        }
546      }
547    }
548
549    protected override void dataGridView_KeyDown(object sender, KeyEventArgs e) {
550      base.dataGridView_KeyDown(sender, e);
551      //data is in read only mode....
552      if (Content.FilterLogic.IsFiltered) return;
553
554      if (e.KeyCode == Keys.Delete) {
555        //Delete column
556        if (dataGridView.SelectedColumns.Count > 0) {
557          var columnsToDelete = dataGridView.SelectedColumns.Cast<DataGridViewColumn>().OrderByDescending(col => col.Index).ToList();
558          foreach (var col in columnsToDelete)
559            Content.DeleteColumn(col.Index);
560        }
561        //Delete row
562        if (dataGridView.SelectedRows.Count > 0) {
563          //necessary if columns are sorted to translate the selected row index
564          var rowIndexes = dataGridView.SelectedRows.Cast<DataGridViewRow>().Select(row => GetRowIndex(row.Index)).ToList();
565          Content.DeleteRows(rowIndexes);
566        }
567      } else if (e.Control && e.KeyCode == Keys.F) {
568        CreateFindAndReplaceDialog();
569        findAndReplaceDialog.ActivateSearch();
570      } else if (e.Control && e.KeyCode == Keys.R) {
571        CreateFindAndReplaceDialog();
572        findAndReplaceDialog.ActivateReplace();
573      }
574    }
575
576    private IDictionary<int, IList<int>> GetSelectedCells() {
577      IDictionary<int, IList<int>> selectedCells = new Dictionary<int, IList<int>>();
578
579      //special case if all cells are selected
580      if (dataGridView.AreAllCellsSelected(true)) {
581        for (int i = 0; i < Content.Columns; i++)
582          selectedCells[i] = Enumerable.Range(0, Content.Rows).ToList();
583        return selectedCells;
584      }
585
586      foreach (var selectedCell in dataGridView.SelectedCells) {
587        var cell = (DataGridViewCell)selectedCell;
588        if (!selectedCells.ContainsKey(cell.ColumnIndex))
589          selectedCells.Add(cell.ColumnIndex, new List<int>(1024));
590        selectedCells[cell.ColumnIndex].Add(cell.RowIndex);
591      }
592
593      return selectedCells;
594    }
595
596    private void StartReplacing() {
597      SuspendRepaint();
598    }
599
600    private void StopReplacing() {
601      ResumeRepaint(true);
602    }
603
604    private void ReplaceTransaction(Action action) {
605      StartReplacing();
606      action();
607      StopReplacing();
608    }
609
610    private void btnSearch_Click(object sender, EventArgs e) {
611      CreateFindAndReplaceDialog();
612      findAndReplaceDialog.ActivateSearch();
613    }
614
615    private void btnReplace_Click(object sender, EventArgs e) {
616      CreateFindAndReplaceDialog();
617      findAndReplaceDialog.ActivateReplace();
618    }
619
620    #region ContextMenu Events
621
622    private void ReplaceWithAverage_Column_Click(object sender, EventArgs e) {
623      ReplaceTransaction(() => {
624        Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), false);
625      });
626    }
627    private void ReplaceWithAverage_Selection_Click(object sender, EventArgs e) {
628      ReplaceTransaction(() => {
629        Content.ManipulationLogic.ReplaceIndicesByAverageValue(GetSelectedCells(), true);
630      });
631    }
632
633    private void ReplaceWithMedian_Column_Click(object sender, EventArgs e) {
634      ReplaceTransaction(() => {
635        Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), false);
636      });
637    }
638    private void ReplaceWithMedian_Selection_Click(object sender, EventArgs e) {
639      ReplaceTransaction(() => {
640        Content.ManipulationLogic.ReplaceIndicesByMedianValue(GetSelectedCells(), true);
641      });
642    }
643
644    private void ReplaceWithRandom_Column_Click(object sender, EventArgs e) {
645      ReplaceTransaction(() => {
646        Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), false);
647      });
648    }
649    private void ReplaceWithRandom_Selection_Click(object sender, EventArgs e) {
650      ReplaceTransaction(() => {
651        Content.ManipulationLogic.ReplaceIndicesByRandomValue(GetSelectedCells(), true);
652      });
653    }
654
655    private void ReplaceWithMostCommon_Column_Click(object sender, EventArgs e) {
656      ReplaceTransaction(() => {
657        Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), false);
658      });
659    }
660    private void ReplaceWithMostCommon_Selection_Click(object sender, EventArgs e) {
661      ReplaceTransaction(() => {
662        Content.ManipulationLogic.ReplaceIndicesByMostCommonValue(GetSelectedCells(), true);
663      });
664    }
665
666    private void ReplaceWithInterpolation_Column_Click(object sender, EventArgs e) {
667      ReplaceTransaction(() => {
668        Content.ManipulationLogic.ReplaceIndicesByLinearInterpolationOfNeighbours(GetSelectedCells());
669      });
670    }
671
672    private void ReplaceWithSmoothing_Selection_Click(object sender, EventArgs e) {
673      ReplaceTransaction(() => {
674        Content.ManipulationLogic.ReplaceIndicesBySmoothing(GetSelectedCells());
675      });
676    }
677    #endregion
678
679    private void addRowButton_Click(object sender, EventArgs e) {
680      Content.PreProcessingData.InsertRow(Content.Rows);
681    }
682
683    private void addColumnButton_Click(object sender, EventArgs e) {
684      Content.PreProcessingData.InsertColumn<double>(Content.Columns.ToString(), Content.Columns);
685    }
686
687    private void renameColumnsButton_Click(object sender, EventArgs e) {
688      var renameDialog = new RenameColumnsDialog(Content.ColumnNames);
689
690      if (renameDialog.ShowDialog(this) == DialogResult.OK) {
691        Content.PreProcessingData.RenameColumns(renameDialog.ColumnNames);
692      }
693    }
694  }
695}
Note: See TracBrowser for help on using the repository browser.