Free cookie consent management tool by TermsFeed Policy Generator

source: branches/New Persistence Exploration/Persistence/HeuristicLab.Persistence.GUI/PersistenceConfigurationForm.cs @ 1405

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

Add empty storable class attributes to classes (#506)

File size: 13.1 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;
11
12namespace HeuristicLab.Persistence.GUI {
13
14  public partial class PersistenceConfigurationForm : Form {
15
16    private readonly Dictionary<string, IFormatter> formatterTable;
17    private readonly Dictionary<IFormatter, string> reverseFormatterTable;   
18    private readonly Dictionary<string, Type> typeNameTable;
19    private readonly Dictionary<Type, string> reverseTypeNameTable;
20
21    public PersistenceConfigurationForm() {
22      InitializeComponent();
23      formatterTable = new Dictionary<string, IFormatter>();
24      reverseFormatterTable = new Dictionary<IFormatter, string>();
25      typeNameTable = new Dictionary<string, Type>();
26      reverseTypeNameTable = new Dictionary<Type, string>();
27      initializeDecomposerList();
28      initializeFormatterPages();
29      //ConfigurationService.Instance.DefineConfiguration(
30      //  XmlFormat.Instance,
31       // new Configuration(
32        //  new Dictionary<Type, IFormatter> {{typeof (bool), new FakeBoolean2XmlFormatter()}},
33         // new List<IDecomposer>{new ArrayDecomposer(), new DictionaryDecomposer()}));         
34      initializeFromConfigurationService();
35    }
36
37    private void initializeFromConfigurationService() {
38      foreach ( IFormat format in ConfigurationService.Instance.Formatters.Keys ) {
39        Configuration config = ConfigurationService.Instance.GetConfiguration(format);
40        foreach (ListViewItem item in decomposerList.Items) {
41          if (item != null) {
42            string name = item.Tag.GetType().AssemblyQualifiedName;
43            item.Checked =
44              config.Decomposers.Count(
45                d => d.GetType().AssemblyQualifiedName == name) > 0;
46             
47          }
48        }
49        foreach ( TabPage page in formatterTabs.TabPages ) {
50          if (page.Tag == format) {
51            DataGridView gridView = (DataGridView)page.Controls.Find("GridView", false)[0];
52            foreach ( DataGridViewRow row in gridView.Rows ) {
53              if (row.Cells["Type"] != null) {
54                IFormatter formatter = config.GetFormatter(typeNameTable[(string) row.Cells["Type"].Value]);
55                if (formatter == null) {
56                  row.Cells["Active"].Value = false;
57                } else {
58                  foreach (var pair in formatterTable) {
59                    if ( pair.Value.GetType().AssemblyQualifiedName == formatter.GetType().AssemblyQualifiedName ) {
60                      row.Cells["Formatter"].Value = pair.Key;
61                      row.Cells["Active"].Value = true;
62                      break;
63                    }
64                  }                               
65                }
66              }             
67            }
68          }
69        }       
70      }
71    }
72
73    private void initializeFormatterPages() {
74      formatterTabs.TabPages.Clear();
75      foreach ( var formats in ConfigurationService.Instance.Formatters ) {
76        TabPage page = new TabPage(formats.Key.Name) {Tag = formats.Key};
77        formatterTabs.TabPages.Add(page);
78        DataGridView gridView = new DataGridView {
79          Name = "GridView",
80          Dock = DockStyle.Fill,
81          EditMode = DataGridViewEditMode.EditOnEnter,
82          AllowUserToAddRows = false,
83          AllowUserToDeleteRows = false,
84          AllowUserToResizeRows = false,
85          AllowUserToOrderColumns = true,
86        };
87        gridView.CellValueChanged += gridView_CellValueChanged;       
88        gridView.Columns.Add(new DataGridViewTextBoxColumn {
89          Name = "Type", ReadOnly = true,
90          AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
91        });
92        gridView.Columns.Add(new DataGridViewCheckBoxColumn {
93          Name = "Active",
94          AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells});
95        gridView.Columns.Add(new DataGridViewComboBoxColumn {
96          Name = "Formatter",
97          AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill});
98        page.Controls.Add(gridView);
99        fillDataGrid(gridView, formats.Value);
100      }
101    }
102
103    private void fillDataGrid(DataGridView gridView, IEnumerable<IFormatter> formatters) {     
104      updateNameTables(formatters);
105      Dictionary<string, List<string>> formatterMap = createFormatterMap(formatters);
106      foreach ( var formatterMapping in formatterMap ) {
107        var row = gridView.Rows[gridView.Rows.Add()];
108        row.Cells["Type"].Value = formatterMapping.Key;
109        row.Cells["Active"].ToolTipText = formatterMapping.Key;
110        row.Cells["Formatter"].Value = true;
111        var comboBoxCell = (DataGridViewComboBoxCell) row.Cells[2];         
112        foreach ( var formatter in formatterMapping.Value ) {
113          comboBoxCell.Items.Add(formatter);
114        }         
115        comboBoxCell.Value = comboBoxCell.Items[0];         
116        comboBoxCell.ToolTipText = comboBoxCell.Items[0].ToString();
117        if (comboBoxCell.Items.Count == 1) {
118          comboBoxCell.ReadOnly = true;
119          comboBoxCell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
120        }     
121      }
122    }
123
124    private Dictionary<string, List<string>> createFormatterMap(IEnumerable<IFormatter> formatters) {
125      var formatterMap = new Dictionary<string, List<string>>();     
126      foreach (var formatter in formatters) {
127        string formatterName = reverseFormatterTable[formatter];
128        string typeName = reverseTypeNameTable[formatter.Type];         
129        if (!formatterMap.ContainsKey(typeName))
130          formatterMap.Add(typeName, new List<string>());
131        formatterMap[typeName].Add(formatterName);
132      }
133      return formatterMap;
134    }
135
136    private void updateNameTables(IEnumerable<IFormatter> formatters) {
137      foreach (var formatter in formatters) {
138        string formatterName = formatter.GetType().Name;
139        if (formatterTable.ContainsKey(formatterName)) {
140          IFormatter otherFormatter = formatterTable[formatterName];
141          formatterTable.Remove(formatterName);
142          reverseFormatterTable.Remove(otherFormatter);
143          formatterTable.Add(otherFormatter.GetType().FullName, otherFormatter);
144          reverseFormatterTable.Add(otherFormatter, otherFormatter.GetType().FullName);
145          formatterName = formatter.GetType().FullName;
146        }
147        formatterTable.Add(formatterName, formatter);
148        reverseFormatterTable.Add(formatter, formatterName);
149
150        string typeName = formatter.Type.IsGenericType ?
151          formatter.Type.SimpleFullName() :
152          formatter.Type.Name;
153        if (typeNameTable.ContainsKey(typeName)) {
154          Type otherType = typeNameTable[typeName];
155          if (otherType != formatter.Type) {
156            typeNameTable.Remove(typeName);
157            reverseTypeNameTable.Remove(otherType);
158            typeNameTable.Add(otherType.FullName, otherType);
159            reverseTypeNameTable.Add(otherType, otherType.FullName);
160            typeName = formatter.Type.FullName;
161            typeNameTable.Add(typeName, formatter.Type);
162            reverseTypeNameTable.Add(formatter.Type, typeName);
163          }
164        } else {
165          typeNameTable.Add(typeName, formatter.Type);
166          reverseTypeNameTable.Add(formatter.Type, typeName);
167        }         
168      }
169    }
170
171    private void initializeDecomposerList() {
172      decomposerList.Items.Clear();
173      foreach ( IDecomposer decomposer in ConfigurationService.Instance.Decomposers ) {
174        var item = decomposerList.Items.Add(decomposer.GetType().Name);
175        item.Checked = true;
176        item.Tag = decomposer;
177      }
178    }
179
180    void gridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
181      UpdatePreview();
182    }   
183
184    private void decomposerList_ItemDrag(object sender, ItemDragEventArgs e) {
185      decomposerList.DoDragDrop(decomposerList.SelectedItems, DragDropEffects.Move);
186    }
187
188    private void decomposerList_DragEnter(object sender, DragEventArgs e) {     
189      if ( e.Data.GetDataPresent(typeof(ListView.SelectedListViewItemCollection).FullName)) {
190        e.Effect = DragDropEffects.Move;
191      }
192    }
193
194    private void decomposerList_DragDrop(object sender, DragEventArgs e) {
195      if (decomposerList.SelectedItems.Count == 0) {
196        return;
197      }
198      Point cp = decomposerList.PointToClient(new Point(e.X, e.Y));     
199      ListViewItem targetItem = decomposerList.GetItemAt(cp.X, cp.Y);     
200      if (targetItem == null)
201        return;           
202      int targetIndex = targetItem.Index;     
203      var selectedItems = new List<ListViewItem>(decomposerList.SelectedItems.Cast<ListViewItem>());
204      int i = 0;
205      foreach ( ListViewItem dragItem in selectedItems ) {               
206        if (targetIndex == dragItem.Index)
207          return;
208        if (dragItem.Index < targetIndex) {
209          decomposerList.Items.Insert(targetIndex + 1, (ListViewItem) dragItem.Clone());
210        } else {
211          decomposerList.Items.Insert(targetIndex + i, (ListViewItem)dragItem.Clone());         
212        }       
213        decomposerList.Items.Remove(dragItem);
214        i++;
215      }
216      UpdatePreview();
217    }
218
219    private void decomposerList_Resize(object sender, EventArgs e) {
220      DecomposersColumn.Width = decomposerList.Width - 4;
221    }
222
223    private IEnumerable<IDecomposer> GetDecomposers() {
224      List<IDecomposer> decomposers = new List<IDecomposer>();
225      foreach ( ListViewItem item in decomposerList.Items ) {
226        if (item != null && item.Checked)
227          decomposers.Add((IDecomposer) item.Tag);
228      }     
229      return decomposers;
230    }
231
232    private void UpdatePreview() {
233      checkBox.Items.Clear();
234      IFormat activeFormat = (IFormat)formatterTabs.SelectedTab.Tag;
235      if (activeFormat != null) {
236        foreach (var formatter in GetCurrentConfiguration(activeFormat).Formatters) {
237          checkBox.Items.Add(formatter.GetType().Name + " (F)");
238        }
239      }
240      foreach (var decomposer in GetDecomposers())
241        checkBox.Items.Add(decomposer.GetType().Name + " (D)");     
242    }
243
244    private void decomposerList_ItemChecked(object sender, ItemCheckedEventArgs e) {
245      UpdatePreview();
246    }
247
248    public Configuration GetCurrentConfiguration(IFormat format) {     
249      Dictionary<Type, IFormatter> formatters = new Dictionary<Type, IFormatter>();
250      foreach ( TabPage page in formatterTabs.TabPages ) {
251        if ( page.Text == format.Name ) {
252          Control[] controls = page.Controls.Find("GridView", false);
253          if (controls.Length == 1) {
254            foreach (DataGridViewRow row in ((DataGridView) controls[0]).Rows) {
255              if ( row.Cells["Type"].Value != null &&
256                   row.Cells["Active"].Value != null &&
257                   row.Cells["Formatter"].Value != null &&
258                   (bool)row.Cells["Active"].Value == true ) {
259                formatters.Add(
260                  typeNameTable[(string)row.Cells["Type"].Value],                 
261                  formatterTable[(string)row.Cells["Formatter"].Value]);
262              }
263            }
264          }
265        }
266      }
267      return new Configuration(formatters, GetDecomposers());
268    }   
269
270    private void updateButton_Click(object sender, EventArgs e) {
271      IFormat format = (IFormat)formatterTabs.SelectedTab.Tag;
272      if (format != null)
273        ConfigurationService.Instance.DefineConfiguration(
274          format,
275          GetCurrentConfiguration(format));
276    }
277   
278  }
279
280  [EmptyStorableClass]
281  public class FakeBoolean2XmlFormatter : IFormatter {   
282
283    public Type Type { get { return typeof (Boolean); } }
284
285    public IFormat Format { get { return XmlFormat.Instance; } }
286
287    public object DoFormat(object o) {
288      return null;
289    }
290
291    public object Parse(object o) {
292      return null;
293    }   
294  } 
295
296  [EmptyStorableClass]
297  public class Int2XmlFormatter: IFormatter {
298    public Type Type { get { return typeof (int);  } }
299    public IFormat Format { get { return XmlFormat.Instance; } }
300    public object DoFormat(object o) {
301      return null;
302    }
303    public object Parse(object o) {
304      return null;
305    }
306  }
307
308  public static class TypeFormatter {
309
310    public static string SimpleFullName(this Type type) {
311      StringBuilder sb = new StringBuilder();
312      SimpleFullName(type, sb);
313      return sb.ToString();
314    }
315
316    private static void SimpleFullName(Type type, StringBuilder sb) {     
317      if (type.IsGenericType) {
318        sb.Append(type.Name, 0, type.Name.LastIndexOf('`'));     
319        sb.Append("<");
320        foreach (Type t in type.GetGenericArguments()) {
321          SimpleFullName(t, sb);         
322          sb.Append(", ");
323        }
324        sb.Remove(sb.Length - 2, 2);
325        sb.Append(">");
326      } else {
327        sb.Append(type.Name);
328      }
329    }
330
331  }
332
333}
Note: See TracBrowser for help on using the repository browser.