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
Line 
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;
11using HeuristicLab.PluginInfrastructure;
12
13namespace HeuristicLab.Persistence.GUI {
14
15  public partial class PersistenceConfigurationForm : Form {
16
17    private readonly Dictionary<string, IFormatter> formatterTable;
18    private readonly Dictionary<string, bool> simpleFormatterTable;
19    private readonly Dictionary<IFormatter, string> reverseFormatterTable;
20    private readonly Dictionary<string, Type> typeNameTable;
21    private readonly Dictionary<Type, string> reverseTypeNameTable;
22
23    public PersistenceConfigurationForm() {
24      InitializeComponent();
25      formatterTable = new Dictionary<string, IFormatter>();
26      simpleFormatterTable = new Dictionary<string, bool>();
27      reverseFormatterTable = new Dictionary<IFormatter, string>();
28      typeNameTable = new Dictionary<string, Type>();
29      reverseTypeNameTable = new Dictionary<Type, string>();
30      InitializeNameTables();
31      initializeConfigPages();
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
54    private void UpdateDecomposerList(ListView decomposerList, Configuration config) {
55      decomposerList.Items.Clear();
56      var availableDecomposers = new Dictionary<string, IDecomposer>();
57      foreach (IDecomposer d in ConfigurationService.Instance.Decomposers) {
58        availableDecomposers.Add(d.GetType().VersionInvariantName(), d);
59      }
60      foreach (IDecomposer decomposer in config.Decomposers) {
61        var item = decomposerList.Items.Add(decomposer.GetType().Name);
62        item.Checked = true;
63        item.Tag = decomposer;
64        availableDecomposers.Remove(decomposer.GetType().VersionInvariantName());
65      }
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      }
71    }
72
73    private void UpdateFromConfigurationService() {
74      foreach (IFormat format in ConfigurationService.Instance.Formats) {
75        Configuration config = ConfigurationService.Instance.GetConfiguration(format);
76        UpdateFormatterGrid(
77          (DataGridView)GetControlsOnPage(format.Name, "GridView"),
78          config);
79        UpdateDecomposerList(
80          (ListView)GetControlsOnPage(format.Name, "DecomposerList"),
81          config);
82      }
83    }
84
85    private void initializeConfigPages() {
86      configurationTabs.TabPages.Clear();
87      foreach (IFormat format in ConfigurationService.Instance.Formats) {
88        List<IFormatter> formatters = ConfigurationService.Instance.Formatters[format.SerialDataType];
89        TabPage page = new TabPage(format.Name) {
90          Name = format.Name,
91          Tag = format,
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();
109        verticalSplit.Panel2.Controls.Add(gridView);
110        fillDataGrid(gridView, formatters);
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",
169        });
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
178    private void fillDataGrid(DataGridView gridView, IEnumerable<IFormatter> formatters) {
179      Dictionary<string, List<string>> formatterMap = createFormatterMap(formatters);
180      foreach (var formatterMapping in formatterMap) {
181        var row = gridView.Rows[gridView.Rows.Add()];
182        row.Cells["Type"].Value = formatterMapping.Key;
183        row.Cells["Type"].ToolTipText = formatterMapping.Key;
184        row.Cells["Active"].Value = true;
185        var comboBoxCell = (DataGridViewComboBoxCell)row.Cells["Formatter"];
186        foreach (var formatter in formatterMapping.Value) {
187          comboBoxCell.Items.Add(formatter);
188        }
189        comboBoxCell.Value = comboBoxCell.Items[0];
190        comboBoxCell.ToolTipText = comboBoxCell.Items[0].ToString();
191        if (comboBoxCell.Items.Count == 1) {
192          comboBoxCell.ReadOnly = true;
193          comboBoxCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
194        }
195      }
196    }
197
198    private Dictionary<string, List<string>> createFormatterMap(IEnumerable<IFormatter> formatters) {
199      var formatterMap = new Dictionary<string, List<string>>();
200      foreach (var formatter in formatters) {
201        string formatterName = reverseFormatterTable[formatter];
202        string typeName = reverseTypeNameTable[formatter.SourceType];
203        if (!formatterMap.ContainsKey(typeName))
204          formatterMap.Add(typeName, new List<string>());
205        formatterMap[typeName].Add(formatterName);
206      }
207      return formatterMap;
208    }
209
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;
223          formatterTable.Add(formatterName, formatter);
224          reverseFormatterTable.Add(formatter, formatterName);
225
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);
243          }
244        }
245      }
246    }
247
248    void gridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
249      UpdatePreview();
250    }
251
252    private void decomposerList_ItemDrag(object sender, ItemDragEventArgs e) {
253      ListView decomposerList = (ListView)sender;
254      decomposerList.DoDragDrop(decomposerList.SelectedItems, DragDropEffects.Move);
255    }
256
257    private void decomposerList_DragEnter(object sender, DragEventArgs e) {
258      if (e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection).FullName)) {
259        e.Effect = DragDropEffects.Move;
260      }
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      }
268      Point cp = decomposerList.PointToClient(new Point(e.X, e.Y));
269      ListViewItem targetItem = decomposerList.GetItemAt(cp.X, cp.Y);
270      if (targetItem == null)
271        return;
272      int targetIndex = targetItem.Index;
273      var selectedItems = new List<ListViewItem>(decomposerList.SelectedItems.Cast<ListViewItem>());
274      int i = 0;
275      foreach (ListViewItem dragItem in selectedItems) {
276        if (targetIndex == dragItem.Index)
277          return;
278        if (dragItem.Index < targetIndex) {
279          decomposerList.Items.Insert(targetIndex + 1, (ListViewItem)dragItem.Clone());
280        } else {
281          decomposerList.Items.Insert(targetIndex + i, (ListViewItem)dragItem.Clone());
282        }
283        decomposerList.Items.Remove(dragItem);
284        i++;
285      }
286      UpdatePreview();
287    }
288
289    private void decomposerList_Resize(object sender, EventArgs e) {
290      ListView decomposerList = (ListView)sender;
291      decomposerList.Columns["DecomposerColumn"].Width = decomposerList.Width - 4;
292    }
293
294    private void UpdatePreview() {
295      ListBox checkBox = (ListBox)GetActiveControl("CheckBox");
296      IFormat activeFormat = (IFormat)configurationTabs.SelectedTab.Tag;
297      if (activeFormat != null && checkBox != null) {
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)
304          checkBox.Items.Add(decomposer.GetType().Name + " (D)");
305      }
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;
318      }
319    }
320
321    private Control GetControlsOnPage(string pageName, string name) {
322      Control[] controls = configurationTabs.TabPages[pageName].Controls.Find(name, true);
323      if (controls.Length == 1) {
324        return controls[0];
325      } else {
326        return null;
327      }
328    }
329
330    private Configuration GenerateConfiguration(IFormat format, DataGridView formatterGrid, ListView decomposerList) {
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      }
349      return new Configuration(format, formatters, decomposers);
350    }
351
352    private Configuration GetActiveConfiguration() {
353      IFormat format = (IFormat)configurationTabs.SelectedTab.Tag;
354      return GenerateConfiguration(format,
355        (DataGridView)GetActiveControl("GridView"),
356        (ListView)GetActiveControl("DecomposerList"));
357    }
358
359    private Configuration GetConfiguration(IFormat format) {
360      return GenerateConfiguration(format,
361       (DataGridView)GetControlsOnPage(format.Name, "GridView"),
362       (ListView)GetControlsOnPage(format.Name, "DecomposerList"));
363    }
364
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());
370    }
371
372  }
373
374  public class Empty : ISerialData { }
375
376  [EmptyStorableClass]
377  public class EmptyFormat : FormatBase<Empty> {
378    public override string Name { get { return "Empty"; } }
379  }
380
381  [EmptyStorableClass]
382  public class EmptyFormatter : FormatterBase<Type, Empty> {
383
384    public override Empty Format(Type o) {
385      return null;
386    }
387
388    public override Type Parse(Empty o) {
389      return null;
390    }
391  }
392
393  [EmptyStorableClass]
394  public class FakeBoolean2XmlFormatter : FormatterBase<bool, Empty> {
395
396    public override Empty Format(bool o) {
397      return null;
398    }
399
400    public override bool Parse(Empty o) {
401      return false;
402    }
403  }
404
405  [EmptyStorableClass]
406  public class Int2XmlFormatter : FormatterBase<int, Empty> {
407
408    public override Empty Format(int o) {
409      return null;
410    }
411
412    public override int Parse(Empty o) {
413      return 0;
414    }
415
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
426    private static void SimpleFullName(Type type, StringBuilder sb) {
427      if (type.IsGenericType) {
428        sb.Append(type.Name, 0, type.Name.LastIndexOf('`'));
429        sb.Append("<");
430        foreach (Type t in type.GetGenericArguments()) {
431          SimpleFullName(t, sb);
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.