Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence.GUI/3.3/PersistenceConfigurationForm.cs @ 1660

Last change on this file since 1660 was 1660, checked in by epitzer, 15 years ago

Display a MessageBox if persistence application settings are corrupted. (#548)

File size: 17.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Drawing;
4using System.Linq;
5using System.Windows.Forms;
6using HeuristicLab.Persistence.Core;
7using HeuristicLab.Persistence.Default.Xml;
8using HeuristicLab.Persistence.Interfaces;
9using System.Text;
10using HeuristicLab.Persistence.Default.Decomposers;
11using HeuristicLab.PluginInfrastructure;
12using HeuristicLab.Persistence.Default.Decomposers.Storable;
13
14namespace HeuristicLab.Persistence.GUI {
15
16  public partial class PersistenceConfigurationForm : Form {
17
18    private readonly Dictionary<string, IFormatter> formatterTable;
19    private readonly Dictionary<string, bool> simpleFormatterTable;
20    private readonly Dictionary<IFormatter, string> reverseFormatterTable;
21    private readonly Dictionary<string, Type> typeNameTable;
22    private readonly Dictionary<Type, string> reverseTypeNameTable;
23    private bool underConstruction;
24
25    public PersistenceConfigurationForm() {
26      InitializeComponent();
27      formatterTable = new Dictionary<string, IFormatter>();
28      simpleFormatterTable = new Dictionary<string, bool>();
29      reverseFormatterTable = new Dictionary<IFormatter, string>();
30      typeNameTable = new Dictionary<string, Type>();
31      reverseTypeNameTable = new Dictionary<Type, string>();
32      underConstruction = true;
33      InitializeTooltips();
34      InitializeNameTables();
35      initializeConfigPages();
36      try {
37        ConfigurationService.Instance.LoadSettings(true);
38        UpdateFromConfigurationService();
39      } catch (PersistenceException e) {
40        MessageBox.Show(
41          "Persistence settings could not be loaded.\r\n" +
42          "Default configurations will be used instead.",
43          "Loading Settings Failed",
44          MessageBoxButtons.OK,
45          MessageBoxIcon.Information);
46      }
47      underConstruction = false;
48      UpdatePreview();
49    }
50
51    private void InitializeTooltips() {
52      ToolTip tooltip = new ToolTip() {
53        AutoPopDelay = 5000,
54        InitialDelay = 1000,
55        ReshowDelay = 500,
56        ShowAlways = true
57      };
58      tooltip.SetToolTip(resetButton,
59        "Clear all custom configurations from memory.\r\n" +
60        "The saved configuration will still be used next\r\n" +
61        "time if you don't save (define) this change.");
62      tooltip.SetToolTip(updateButton,
63        "Define configuration for currently active format\r\n" +
64        "and save to disk.");
65    }
66
67    private void UpdateFormatterGrid(DataGridView formatterGrid, Configuration config) {
68      foreach (DataGridViewRow row in formatterGrid.Rows) {
69        if (row.Cells["Type"] != null) {
70          IFormatter formatter = config.GetFormatter(typeNameTable[(string)row.Cells["Type"].Value]);
71          if (formatter == null) {
72            row.Cells["Active"].Value = false;
73          } else {
74            foreach (var pair in formatterTable) {
75              if (pair.Value.GetType().VersionInvariantName() == formatter.GetType().VersionInvariantName()) {
76                row.Cells["Formatter"].Value = pair.Key;
77                row.Cells["Active"].Value = true;
78                break;
79              }
80            }
81          }
82        }
83      }
84    }
85
86    private void UpdateDecomposerList(ListView decomposerList, Configuration config) {
87      decomposerList.SuspendLayout();
88      decomposerList.Items.Clear();
89      var availableDecomposers = new Dictionary<string, IDecomposer>();
90      foreach (IDecomposer d in ConfigurationService.Instance.Decomposers) {
91        availableDecomposers.Add(d.GetType().VersionInvariantName(), d);
92      }
93      foreach (IDecomposer decomposer in config.Decomposers) {
94        var item = decomposerList.Items.Add(decomposer.GetType().Name);
95        item.Checked = true;
96        item.Tag = decomposer;
97        availableDecomposers.Remove(decomposer.GetType().VersionInvariantName());
98      }
99      foreach (KeyValuePair<string, IDecomposer> pair in availableDecomposers) {
100        var item = decomposerList.Items.Add(pair.Value.GetType().Name);
101        item.Checked = false;
102        item.Tag = pair.Value;
103      }
104      decomposerList.ResumeLayout();
105    }
106
107    private void UpdateFromConfigurationService() {
108      configurationTabs.SuspendLayout();
109      foreach (IFormat format in ConfigurationService.Instance.Formats) {
110        Configuration config = ConfigurationService.Instance.GetConfiguration(format);
111        UpdateFormatterGrid(
112          (DataGridView)GetControlsOnPage(format.Name, "GridView"),
113          config);
114        UpdateDecomposerList(
115          (ListView)GetControlsOnPage(format.Name, "DecomposerList"),
116          config);
117      }
118      configurationTabs.ResumeLayout();
119    }
120
121    private void initializeConfigPages() {
122      configurationTabs.SuspendLayout();
123      configurationTabs.TabPages.Clear();
124      foreach (IFormat format in ConfigurationService.Instance.Formats) {
125        List<IFormatter> formatters = ConfigurationService.Instance.Formatters[format.SerialDataType];
126        TabPage page = new TabPage(format.Name) {
127          Name = format.Name,
128          Tag = format,
129        };
130        page.SuspendLayout();
131        configurationTabs.TabPages.Add(page);
132        SplitContainer verticalSplit = new SplitContainer {
133          Dock = DockStyle.Fill,
134          Orientation = Orientation.Vertical,
135          BorderStyle = BorderStyle.Fixed3D,
136        };
137        verticalSplit.SuspendLayout();
138        page.Controls.Add(verticalSplit);
139        SplitContainer horizontalSplit = new SplitContainer {
140          Dock = DockStyle.Fill,
141          Orientation = Orientation.Horizontal,
142          BorderStyle = BorderStyle.Fixed3D,
143        };
144        horizontalSplit.SuspendLayout();
145        verticalSplit.Panel1.Controls.Add(horizontalSplit);
146        ListView decomposerList = createDecomposerList();
147        horizontalSplit.Panel1.Controls.Add(decomposerList);
148        DataGridView gridView = createGridView();
149        verticalSplit.Panel2.Controls.Add(gridView);
150        fillDataGrid(gridView, formatters);
151        ListBox checkBox = new ListBox {
152          Name = "CheckBox",
153          Dock = DockStyle.Fill,
154        };
155        horizontalSplit.Panel2.Controls.Add(checkBox);
156        horizontalSplit.ResumeLayout();
157        verticalSplit.ResumeLayout();
158        page.ResumeLayout();
159      }
160      configurationTabs.ResumeLayout();
161    }
162
163    private DataGridView createGridView() {
164      DataGridView gridView = new DataGridView {
165        Name = "GridView",
166        Dock = DockStyle.Fill,
167        RowHeadersVisible = false,
168        MultiSelect = false,
169        EditMode = DataGridViewEditMode.EditOnEnter,
170        AllowUserToAddRows = false,
171        AllowUserToDeleteRows = false,
172        AllowUserToResizeRows = false,
173        AllowUserToOrderColumns = true,
174      };
175      gridView.SuspendLayout();
176      gridView.CellValueChanged += gridView_CellValueChanged;
177      gridView.Columns.Add(new DataGridViewTextBoxColumn {
178        Name = "Type", ReadOnly = true,
179        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
180      });
181      gridView.Columns.Add(new DataGridViewCheckBoxColumn {
182        Name = "Active",
183        AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
184      });
185      gridView.Columns.Add(new DataGridViewComboBoxColumn {
186        Name = "Formatter",
187        AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
188      });
189      gridView.ResumeLayout();
190      return gridView;
191    }
192
193    private ListView createDecomposerList() {
194      ListView decomposerList = new ListView {
195        Activation = ItemActivation.OneClick,
196        AllowDrop = true,
197        CheckBoxes = true,
198        Dock = DockStyle.Fill,
199        FullRowSelect = true,
200        GridLines = true,
201        HeaderStyle = ColumnHeaderStyle.Nonclickable,
202        Name = "DecomposerList",
203        ShowGroups = false,
204        View = View.Details
205      };
206      decomposerList.SuspendLayout();
207      decomposerList.Resize += decomposerList_Resize;
208      decomposerList.ItemChecked += decomposerList_ItemChecked;
209      decomposerList.DragDrop += decomposerList_DragDrop;
210      decomposerList.DragEnter += decomposerList_DragEnter;
211      decomposerList.ItemDrag += decomposerList_ItemDrag;
212      decomposerList.Columns.Add(
213        new ColumnHeader {
214          Name = "DecomposerColumn", Text = "Decomposers",
215        });
216      foreach (IDecomposer decomposer in ConfigurationService.Instance.Decomposers) {
217        var item = decomposerList.Items.Add(decomposer.GetType().Name);
218        item.Checked = true;
219        item.Tag = decomposer;
220      }
221      decomposerList.ResumeLayout();
222      return decomposerList;
223    }
224
225    private void fillDataGrid(DataGridView gridView, IEnumerable<IFormatter> formatters) {
226      gridView.SuspendLayout();
227      Dictionary<string, List<string>> formatterMap = createFormatterMap(formatters);
228      foreach (var formatterMapping in formatterMap) {
229        var row = gridView.Rows[gridView.Rows.Add()];
230        row.Cells["Type"].Value = formatterMapping.Key;
231        row.Cells["Type"].ToolTipText = formatterMapping.Key;
232        row.Cells["Active"].Value = true;
233        var comboBoxCell = (DataGridViewComboBoxCell)row.Cells["Formatter"];
234        foreach (var formatter in formatterMapping.Value) {
235          comboBoxCell.Items.Add(formatter);
236        }
237        comboBoxCell.Value = comboBoxCell.Items[0];
238        comboBoxCell.ToolTipText = comboBoxCell.Items[0].ToString();
239        if (comboBoxCell.Items.Count == 1) {
240          comboBoxCell.ReadOnly = true;
241          comboBoxCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
242        }
243      }
244      gridView.ResumeLayout();
245    }
246
247    private Dictionary<string, List<string>> createFormatterMap(IEnumerable<IFormatter> formatters) {
248      var formatterMap = new Dictionary<string, List<string>>();
249      foreach (var formatter in formatters) {
250        string formatterName = reverseFormatterTable[formatter];
251        string typeName = reverseTypeNameTable[formatter.SourceType];
252        if (!formatterMap.ContainsKey(typeName))
253          formatterMap.Add(typeName, new List<string>());
254        formatterMap[typeName].Add(formatterName);
255      }
256      return formatterMap;
257    }
258
259    private void InitializeNameTables() {
260      foreach (var serialDataType in ConfigurationService.Instance.Formatters.Keys) {
261        foreach (var formatter in ConfigurationService.Instance.Formatters[serialDataType]) {
262          string formatterName = formatter.GetType().Name;
263          if (simpleFormatterTable.ContainsKey(formatterName)) {
264            IFormatter otherFormatter = formatterTable[formatterName];
265            formatterTable.Remove(formatterName);
266            reverseFormatterTable.Remove(otherFormatter);
267            formatterTable.Add(otherFormatter.GetType().VersionInvariantName(), otherFormatter);
268            reverseFormatterTable.Add(otherFormatter, otherFormatter.GetType().VersionInvariantName());
269            formatterName = formatter.GetType().VersionInvariantName();
270          }
271          simpleFormatterTable[formatter.GetType().Name] = true;
272          formatterTable.Add(formatterName, formatter);
273          reverseFormatterTable.Add(formatter, formatterName);
274
275          string typeName = formatter.SourceType.IsGenericType ?
276            formatter.SourceType.SimpleFullName() :
277            formatter.SourceType.Name;
278          if (typeNameTable.ContainsKey(typeName)) {
279            Type otherType = typeNameTable[typeName];
280            if (otherType != formatter.SourceType) {
281              typeNameTable.Remove(typeName);
282              reverseTypeNameTable.Remove(otherType);
283              typeNameTable.Add(otherType.VersionInvariantName(), otherType);
284              reverseTypeNameTable.Add(otherType, otherType.VersionInvariantName());
285              typeName = formatter.SourceType.VersionInvariantName();
286              typeNameTable.Add(typeName, formatter.SourceType);
287              reverseTypeNameTable.Add(formatter.SourceType, typeName);
288            }
289          } else {
290            typeNameTable.Add(typeName, formatter.SourceType);
291            reverseTypeNameTable.Add(formatter.SourceType, typeName);
292          }
293        }
294      }
295    }
296
297    private void UpdatePreview() {
298      if (underConstruction)
299        return;
300      ListBox checkBox = (ListBox)GetActiveControl("CheckBox");
301      checkBox.SuspendLayout();
302      IFormat activeFormat = (IFormat)configurationTabs.SelectedTab.Tag;
303      if (activeFormat != null && checkBox != null) {
304        checkBox.Items.Clear();
305        Configuration activeConfig = GetActiveConfiguration();
306        foreach (var formatter in activeConfig.Formatters) {
307          checkBox.Items.Add(formatter.GetType().Name + " (F)");
308        }
309        foreach (var decomposer in activeConfig.Decomposers)
310          checkBox.Items.Add(decomposer.GetType().Name + " (D)");
311      }
312      checkBox.ResumeLayout();
313    }
314
315
316    void gridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
317      UpdatePreview();
318    }
319
320    private void decomposerList_ItemDrag(object sender, ItemDragEventArgs e) {
321      ListView decomposerList = (ListView)sender;
322      decomposerList.DoDragDrop(decomposerList.SelectedItems, DragDropEffects.Move);
323    }
324
325    private void decomposerList_DragEnter(object sender, DragEventArgs e) {
326      if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection).FullName)) {
327        e.Effect = DragDropEffects.Move;
328      }
329    }
330
331    private void decomposerList_DragDrop(object sender, DragEventArgs e) {
332      ListView decomposerList = (ListView)sender;
333      if (decomposerList.SelectedItems.Count == 0) {
334        return;
335      }
336      Point cp = decomposerList.PointToClient(new Point(e.X, e.Y));
337      ListViewItem targetItem = decomposerList.GetItemAt(cp.X, cp.Y);
338      if (targetItem == null)
339        return;
340      int targetIndex = targetItem.Index;
341      var selectedItems = new List<ListViewItem>(decomposerList.SelectedItems.Cast<ListViewItem>());
342      int i = 0;
343      foreach (ListViewItem dragItem in selectedItems) {
344        if (targetIndex == dragItem.Index)
345          return;
346        if (dragItem.Index < targetIndex) {
347          decomposerList.Items.Insert(targetIndex + 1, (ListViewItem)dragItem.Clone());
348        } else {
349          decomposerList.Items.Insert(targetIndex + i, (ListViewItem)dragItem.Clone());
350        }
351        decomposerList.Items.Remove(dragItem);
352        i++;
353      }
354      UpdatePreview();
355    }
356
357    private void decomposerList_Resize(object sender, EventArgs e) {
358      ListView decomposerList = (ListView)sender;
359      decomposerList.Columns["DecomposerColumn"].Width = decomposerList.Width - 4;
360    }
361
362
363    private void decomposerList_ItemChecked(object sender, ItemCheckedEventArgs e) {
364      UpdatePreview();
365    }
366
367    private Control GetActiveControl(string name) {
368      Control[] controls = configurationTabs.SelectedTab.Controls.Find(name, true);
369      if (controls.Length == 1) {
370        return controls[0];
371      } else {
372        return null;
373      }
374    }
375
376    private Control GetControlsOnPage(string pageName, string name) {
377      Control[] controls = configurationTabs.TabPages[pageName].Controls.Find(name, true);
378      if (controls.Length == 1) {
379        return controls[0];
380      } else {
381        return null;
382      }
383    }
384
385    private Configuration GenerateConfiguration(IFormat format, DataGridView formatterGrid, ListView decomposerList) {
386      if (formatterGrid == null || decomposerList == null)
387        return null;
388      var formatters = new List<IFormatter>();
389      foreach (DataGridViewRow row in formatterGrid.Rows) {
390        if (row.Cells["Type"].Value != null &&
391             row.Cells["Active"].Value != null &&
392             row.Cells["Formatter"].Value != null &&
393             (bool)row.Cells["Active"].Value == true) {
394          formatters.Add(formatterTable[(string)row.Cells["Formatter"].Value]);
395        }
396      }
397      var decomposers = new List<IDecomposer>();
398      foreach (ListViewItem item in decomposerList.Items) {
399        if (item != null && item.Checked)
400          decomposers.Add((IDecomposer)item.Tag);
401      }
402      return new Configuration(format, formatters, decomposers);
403    }
404
405    private Configuration GetActiveConfiguration() {
406      IFormat format = (IFormat)configurationTabs.SelectedTab.Tag;
407      return GenerateConfiguration(format,
408        (DataGridView)GetActiveControl("GridView"),
409        (ListView)GetActiveControl("DecomposerList"));
410    }
411
412    private Configuration GetConfiguration(IFormat format) {
413      return GenerateConfiguration(format,
414       (DataGridView)GetControlsOnPage(format.Name, "GridView"),
415       (ListView)GetControlsOnPage(format.Name, "DecomposerList"));
416    }
417
418    private void updateButton_Click(object sender, EventArgs e) {
419      IFormat format = (IFormat)configurationTabs.SelectedTab.Tag;
420      if (format != null)
421        ConfigurationService.Instance.DefineConfiguration(
422          GetActiveConfiguration());
423    }
424
425    private void resetButton_Click(object sender, EventArgs e) {
426      ConfigurationService.Instance.Reset();
427      underConstruction = true;
428      UpdateFromConfigurationService();
429      underConstruction = false;
430      UpdatePreview();
431    }
432
433  }
434
435 
436
437}
Note: See TracBrowser for help on using the repository browser.