Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.cs @ 6988

Last change on this file since 6988 was 6803, checked in by mkommend, 13 years ago

#1479: Merged grammar editor branch into trunk.

File size: 16.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Common;
28using HeuristicLab.Core.Views;
29using HeuristicLab.MainForm;
30using HeuristicLab.PluginInfrastructure;
31
32namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
33  [View("Symbolic Expression Grammar Editor")]
34  [Content(typeof(ISymbolicExpressionGrammar), true)]
35  public partial class SymbolicExpressionGrammarEditorView : NamedItemView {
36    public SymbolicExpressionGrammarEditorView() {
37      InitializeComponent();
38    }
39
40    public override bool ReadOnly {
41      get {
42        if ((Content != null) && Content.ReadOnly) return true;
43        return base.ReadOnly;
44      }
45      set {
46        if ((Content != null) && Content.ReadOnly) base.ReadOnly = true;
47        else base.ReadOnly = value;
48      }
49    }
50
51    public new ISymbolicExpressionGrammar Content {
52      get { return (ISymbolicExpressionGrammar)base.Content; }
53      set { base.Content = value; }
54    }
55
56    protected override void SetEnabledStateOfControls() {
57      base.SetEnabledStateOfControls();
58      addButton.Enabled = Content != null && !Content.ReadOnly;
59      removeButton.Enabled = Content != null && !Content.ReadOnly && symbolsTreeView.SelectedNode != null && !(symbolsTreeView.SelectedNode.Tag is IReadOnlySymbol);
60      copyButton.Enabled = Content != null && !Content.ReadOnly && symbolsTreeView.SelectedNode != null && !(symbolsTreeView.SelectedNode.Tag is IReadOnlySymbol);
61    }
62
63    protected override void OnContentChanged() {
64      base.OnContentChanged();
65      if (Content != null) {
66        symbolsTreeView.Nodes.Clear();
67        UpdateSymbolsTreeView();
68
69        symbolsTreeView.CollapseAll();
70        foreach (var node in IterateTreeNodes())
71          if (node.Checked) node.Expand();
72
73        allowedChildSymbolsControl.Grammar = Content;
74        allowedChildSymbolsControl.Symbol = null;
75        symbolDetailsViewHost.Content = null;
76      } else {
77        symbolsTreeView.Nodes.Clear();
78        allowedChildSymbolsControl.Grammar = null;
79        symbolDetailsViewHost.Content = null;
80      }
81    }
82
83    #region events
84    protected override void RegisterContentEvents() {
85      base.RegisterContentEvents();
86      Content.ReadOnlyChanged += new System.EventHandler(Content_ReadOnlyChanged);
87      Content.Changed += new System.EventHandler(Content_Changed);
88    }
89    protected override void DeregisterContentEvents() {
90      Content.ReadOnlyChanged -= new System.EventHandler(Content_ReadOnlyChanged);
91      Content.Changed -= new System.EventHandler(Content_Changed);
92      base.DeregisterContentEvents();
93    }
94
95    private void Content_ReadOnlyChanged(object sender, EventArgs e) {
96      ReadOnly = Content.ReadOnly;
97    }
98
99    private void Content_Changed(object sender, EventArgs e) {
100      ISymbol symbol = null;
101      if (symbolsTreeView.SelectedNode != null)
102        symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
103
104      allowedChildSymbolsControl.Grammar = Content;
105
106      UpdateSymbolsTreeView();
107      if (symbol != null && Content.ContainsSymbol(symbol)) {
108        symbolsTreeView.SelectedNode = IterateTreeNodes().Where(n => n.Tag == symbol).ToList().FirstOrDefault();
109        UpdateSymbolDetailsViews();
110      }
111    }
112    #endregion
113
114    private void UpdateSymbolsTreeView() {
115      var symbols = Content.Symbols.ToList();
116      foreach (var treeNode in IterateTreeNodes().ToList()) {
117        var symbol = treeNode.Tag as ISymbol;
118        if (!symbols.Contains(symbol))
119          treeNode.Remove();
120      }
121
122      var groupSymbols = symbols.OfType<GroupSymbol>().ToList();
123      var topLevelSymbols = Content.Symbols.Where(s => !groupSymbols.Any(g => g.Symbols.Contains(s)));
124      UpdateChildTreeNodes(symbolsTreeView.Nodes, topLevelSymbols);
125
126      RebuildImageList();
127    }
128
129    private void UpdateChildTreeNodes(TreeNodeCollection collection, IEnumerable<ISymbol> symbols) {
130      foreach (ISymbol symbol in symbols) {
131        TreeNode node = collection.Cast<TreeNode>().Where(n => n.Tag == symbol).FirstOrDefault();
132        if (node == null) {
133          node = new TreeNode();
134          node.Tag = symbol;
135          collection.Add(node);
136        }
137        node.Checked = symbol.Enabled;
138        node.Text = symbol.Name;
139
140        var groupSymbol = symbol as GroupSymbol;
141        if (groupSymbol != null) UpdateChildTreeNodes(node.Nodes, groupSymbol.Symbols);
142      }
143    }
144
145    private void symbolsTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
146      if (e.Action != TreeViewAction.Unknown) UpdateSymbolDetailsViews();
147
148      removeButton.Enabled = symbolsTreeView.SelectedNode != null && !(symbolsTreeView.SelectedNode.Tag is IReadOnlySymbol);
149      copyButton.Enabled = symbolsTreeView.SelectedNode != null && !(symbolsTreeView.SelectedNode.Tag is IReadOnlySymbol);
150    }
151
152    private void symbolsTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
153      if (e.Action != TreeViewAction.Unknown) {
154        Content.StartGrammarManipulation();
155        allowedChildSymbolsControl.Symbol = null;
156        var symbol = (ISymbol)e.Node.Tag;
157        symbol.Enabled = e.Node.Checked;
158        foreach (var node in IterateTreeNodes())
159          node.Checked = ((ISymbol)node.Tag).Enabled;
160
161        Content.FinishedGrammarManipulation();
162      }
163    }
164
165    #region drag & drop operations
166    private GroupSymbol parentOfDraggedSymbol;
167    private void symbolsTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
168      if (!Locked) {
169        var treeNode = e.Item as TreeNode;
170        if (treeNode.Parent != null) parentOfDraggedSymbol = treeNode.Parent.Tag as GroupSymbol;
171        var data = new DataObject();
172        data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, treeNode.Tag);
173        validDragOperation = true;
174        DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Move);
175      }
176    }
177
178
179    private bool validDragOperation;
180    private void symbolsTreeView_DragEnter(object sender, DragEventArgs e) {
181      validDragOperation = false;
182      if (Content == null) return;
183
184      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
185      var symbol = data as ISymbol;
186      if (symbol != null && !(symbol is IReadOnlySymbol)) validDragOperation = true;
187    }
188    private void symbolsTreeView_DragOver(object sender, DragEventArgs e) {
189      e.Effect = DragDropEffects.None;
190      if (validDragOperation) {
191        GroupSymbol groupSymbol = null;
192        Point mouse = symbolsTreeView.PointToClient(new Point(e.X, e.Y));
193        TreeNode node = symbolsTreeView.GetNodeAt(mouse);
194        if (node == null) return;
195        groupSymbol = node.Tag as GroupSymbol;
196        if (groupSymbol == null) return;
197        var symbol = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
198        if (symbol == groupSymbol) return;
199
200        if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
201      }
202    }
203    private void symbolsTreeView_DragDrop(object sender, DragEventArgs e) {
204      var symbol = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as ISymbol;
205
206      GroupSymbol groupSymbol = null;
207      Point mouse = symbolsTreeView.PointToClient(new Point(e.X, e.Y));
208      TreeNode node = symbolsTreeView.GetNodeAt(mouse);
209      if (node != null) groupSymbol = node.Tag as GroupSymbol;
210      if (node != null && groupSymbol == null) groupSymbol = node.Parent.Tag as GroupSymbol;
211
212      Content.StartGrammarManipulation();
213      Cloner cloner = new Cloner();
214      var clonedSymbol = cloner.Clone(symbol);
215      ChangeDuplicateSymbolNames(clonedSymbol);
216
217      if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(clonedSymbol);
218      else Content.AddSymbol(clonedSymbol);
219
220      UpdateGrammerConstraintsForClonedSymbol(symbol, cloner);
221      Content.FinishedGrammarManipulation();
222    }
223    #endregion
224
225    private void symbolsTreeView_MouseDown(object sender, MouseEventArgs e) {
226      // enables deselection of treeNodes
227      Point coordinates = new Point(e.X, e.Y);
228      TreeNode node = symbolsTreeView.GetNodeAt(coordinates);
229      if (e.Button == System.Windows.Forms.MouseButtons.Left && node == null) {
230        symbolsTreeView.SelectedNode = null;
231        symbolDetailsViewHost.Content = null;
232        SetEnabledStateOfControls();
233      }
234    }
235
236    private void symbolsTreeView_KeyDown(object sender, KeyEventArgs e) {
237      if (ReadOnly) return;
238      if (symbolsTreeView.SelectedNode == null) return;
239      if (e.KeyCode != Keys.Delete) return;
240
241      var symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
242      if (!(symbol is IReadOnlySymbol))
243        Content.RemoveSymbol(symbol);
244
245      SetEnabledStateOfControls();
246      UpdateSymbolDetailsViews();
247      RebuildImageList();
248    }
249
250    #region button events
251    private TypeSelectorDialog typeSelectorDialog;
252    private void addButton_Click(object sender, EventArgs e) {
253      if (typeSelectorDialog == null) {
254        typeSelectorDialog = new TypeSelectorDialog();
255        typeSelectorDialog.Caption = "Select Symbol";
256        typeSelectorDialog.TypeSelector.Caption = "Available Symbols";
257        typeSelectorDialog.TypeSelector.Configure(typeof(ISymbol), false, false, (t) => { return !typeof(IReadOnlySymbol).IsAssignableFrom(t); });
258      }
259      if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
260        try {
261          ISymbol symbol = (ISymbol)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
262          ChangeDuplicateSymbolNames(symbol);
263          GroupSymbol groupSymbol = null;
264
265          TreeNode selectedNode = symbolsTreeView.SelectedNode;
266          if (selectedNode != null) {
267            groupSymbol = selectedNode.Tag as GroupSymbol;
268            if (groupSymbol == null && selectedNode.Parent != null) groupSymbol = selectedNode.Parent.Tag as GroupSymbol;
269          }
270          if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(symbol);
271          else Content.AddSymbol(symbol);
272        }
273        catch (Exception ex) {
274          ErrorHandling.ShowErrorDialog(this, ex);
275        }
276      }
277    }
278
279    private void copyButton_Click(object sender, EventArgs e) {
280      var symbol = symbolsTreeView.SelectedNode.Tag as ISymbol;
281      if (symbol != null && !(symbol is IReadOnlySymbol)) {
282
283        Content.StartGrammarManipulation();
284        Cloner cloner = new Cloner();
285        var clonedSymbol = cloner.Clone(symbol);
286        ChangeDuplicateSymbolNames(clonedSymbol);
287
288        GroupSymbol groupSymbol = null;
289        if (symbolsTreeView.SelectedNode.Parent != null) groupSymbol = symbolsTreeView.SelectedNode.Parent.Tag as GroupSymbol;
290
291        if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(clonedSymbol);
292        else Content.AddSymbol(clonedSymbol);
293
294        UpdateGrammerConstraintsForClonedSymbol(symbol, cloner);
295        Content.FinishedGrammarManipulation();
296      }
297    }
298
299    private void removeButton_Click(object sender, EventArgs e) {
300      var symbol = symbolsTreeView.SelectedNode.Tag as ISymbol;
301      if (symbol != null && !(symbol is IReadOnlySymbol)) {
302        Content.RemoveSymbol(symbol);
303      }
304    }
305
306    private void showDetailsCheckBox_CheckedChanged(object sender, EventArgs e) {
307      splitContainer1.Panel2Collapsed = !showDetailsCheckBox.Checked;
308    }
309
310    private void showSampleTreeButton_Click(object sender, EventArgs e) {
311      SymbolicExpressionGrammarSampleExpressionTreeView view = new SymbolicExpressionGrammarSampleExpressionTreeView();
312      view.Content = Content;
313      view.Show();
314    }
315
316    #endregion
317
318    #region helpers
319    private void UpdateGrammerConstraintsForClonedSymbol(ISymbol symbol, Cloner cloner) {
320      foreach (var s in symbol.Flatten().Where(x => !(x is GroupSymbol))) {
321        if (!cloner.ClonedObjectRegistered(s)) throw new InvalidOperationException();
322        var clone = cloner.Clone(s);
323        Content.SetSubtreeCount(clone, Content.GetMinimumSubtreeCount(s), Content.GetMaximumSubtreeCount(s));
324        foreach (var childSymbol in Content.GetAllowedChildSymbols(s)) {
325          var newChildSymbol = childSymbol;
326          if (cloner.ClonedObjectRegistered(childSymbol)) newChildSymbol = cloner.Clone(childSymbol);
327          Content.AddAllowedChildSymbol(clone, newChildSymbol);
328        }
329        for (int i = 0; i < Content.GetMaximumSubtreeCount(s); i++) {
330          foreach (var childSymbol in Content.GetAllowedChildSymbols(s, i)) {
331            var newChildSymbol = childSymbol;
332            if (cloner.ClonedObjectRegistered(childSymbol)) newChildSymbol = cloner.Clone(childSymbol);
333            Content.AddAllowedChildSymbol(clone, newChildSymbol, i);
334          }
335        }
336      }
337    }
338
339    private void ChangeDuplicateSymbolNames(ISymbol symbol) {
340      foreach (var s in symbol.Flatten()) {
341        var originalSymbolName = s.Name;
342        int i = 1;
343        while (Content.ContainsSymbol(s)) {
344          s.Name = originalSymbolName + i;
345          i++;
346        }
347      }
348    }
349
350    private void UpdateSymbolDetailsViews() {
351      if (symbolsTreeView.SelectedNode != null) {
352        symbolDetailsViewHost.Content = (ISymbol)symbolsTreeView.SelectedNode.Tag;
353        allowedChildSymbolsControl.Symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
354      } else {
355        symbolDetailsViewHost.Content = null;
356        allowedChildSymbolsControl.Symbol = null;
357      }
358    }
359
360    private IEnumerable<TreeNode> IterateTreeNodes(TreeNode node = null) {
361      TreeNodeCollection nodes;
362      if (node == null)
363        nodes = symbolsTreeView.Nodes;
364      else {
365        nodes = node.Nodes;
366        yield return node;
367      }
368
369      foreach (var childNode in nodes.OfType<TreeNode>())
370        foreach (var n in IterateTreeNodes(childNode))
371          yield return n;
372    }
373
374    protected virtual void RebuildImageList() {
375      symbolsTreeView.ImageList.Images.Clear();
376      foreach (TreeNode treeNode in IterateTreeNodes()) {
377        var symbol = (ISymbol)treeNode.Tag;
378        symbolsTreeView.ImageList.Images.Add(symbol == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : symbol.ItemImage);
379        treeNode.ImageIndex = symbolsTreeView.ImageList.Images.Count - 1;
380      }
381    }
382
383    //necessary code to handle dock correctly regarding the expanded nodes
384    bool[] expandendedState;
385    protected override void OnHandleCreated(EventArgs e) {
386      base.OnHandleCreated(e);
387      if (expandendedState == null) return;
388      var nodes = IterateTreeNodes().ToList();
389      for (int i = 0; i < nodes.Count; i++)
390        if (expandendedState[i]) nodes[i].Expand();
391    }
392    protected override void OnHandleDestroyed(EventArgs e) {
393      base.OnHandleDestroyed(e);
394      var nodes = IterateTreeNodes().ToList();
395      expandendedState = new bool[nodes.Count];
396      for (int i = 0; i < nodes.Count; i++)
397        expandendedState[i] = nodes[i].IsExpanded;
398    }
399    #endregion
400  }
401
402  //this class is necessary to prevent double clicks which do not fire the checkbox checked event
403  internal class CheckBoxTreeView : TreeView {
404    protected override void WndProc(ref Message m) {
405      // Suppress WM_LBUTTONDBLCLK
406      if (m.Msg == 0x203) { m.Result = IntPtr.Zero; } else base.WndProc(ref m);
407    }
408  }
409}
Note: See TracBrowser for help on using the repository browser.