Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 3975 was 3742, checked in by gkronber, 15 years ago

Fixed GPL license headers and deleted files which are not referenced by projects. #893

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