Free cookie consent management tool by TermsFeed Policy Generator

source: branches/irace/HeuristicLab.Persistence.GUI/3.3/PersistenceConfigurationForm.cs @ 11552

Last change on this file since 11552 was 11172, checked in by ascheibe, 10 years ago

#2115 updated missing copyrights in trunk

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