Free cookie consent management tool by TermsFeed Policy Generator

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

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

Namespace refactoring: rename formatters & decomposers -> primitive and composite serializers. (#603)

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