Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 1584 was 1566, checked in by epitzer, 16 years ago

Format white space. (Ctrl-K, Ctrl-D) (#548)

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