Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2994-AutoDiffForIntervals/HeuristicLab.Persistence.GUI/3.3/PersistenceConfigurationForm.cs @ 17285

Last change on this file since 17285 was 17209, checked in by gkronber, 5 years ago

#2994: merged r17132:17198 from trunk to branch

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