Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs @ 10487

Last change on this file since 10487 was 10487, checked in by bburlacu, 11 years ago

#2076: Fixed image save to file in the SymbolicExpressionTreeChart. Removed commented code from SymbolicExpressionTreeLayoutAdapter.

File size: 17.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.Drawing.Imaging;
26using System.IO;
27using System.Linq;
28using System.Windows.Forms;
29using Point = System.Drawing.Point;
30
31namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
32  public partial class SymbolicExpressionTreeChart : UserControl {
33    private Image image;
34    private readonly StringFormat stringFormat;
35    private Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode> visualTreeNodes;
36    private Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection> visualLines;
37    private readonly ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode> layoutEngine;
38    private readonly SymbolicExpressionTreeLayoutAdapter layoutAdapter;
39
40    private const int preferredNodeWidth = 70;
41    private const int preferredNodeHeight = 46;
42    private const int minHorizontalDistance = 20;
43    private const int minVerticalDistance = 20;
44
45
46    public SymbolicExpressionTreeChart() {
47      InitializeComponent();
48      this.image = new Bitmap(Width, Height);
49      this.stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
50      this.spacing = 5;
51      this.lineColor = Color.Black;
52      this.backgroundColor = Color.White;
53      this.textFont = new Font(FontFamily.GenericSansSerif, 12);
54      layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
55      layoutAdapter = new SymbolicExpressionTreeLayoutAdapter();
56    }
57
58    public SymbolicExpressionTreeChart(ISymbolicExpressionTree tree)
59      : this() {
60      layoutEngine = new ReingoldTilfordLayoutEngine<ISymbolicExpressionTreeNode>();
61      layoutAdapter = new SymbolicExpressionTreeLayoutAdapter();
62      this.Tree = tree;
63    }
64
65    #region Public properties
66    private int spacing;
67    public int Spacing {
68      get { return this.spacing; }
69      set {
70        this.spacing = value;
71        this.Repaint();
72      }
73    }
74
75    private Color lineColor;
76    public Color LineColor {
77      get { return this.lineColor; }
78      set {
79        this.lineColor = value;
80        this.Repaint();
81      }
82    }
83
84    private Color backgroundColor;
85    public Color BackgroundColor {
86      get { return this.backgroundColor; }
87      set {
88        this.backgroundColor = value;
89        this.Repaint();
90      }
91    }
92
93    private Font textFont;
94    public Font TextFont {
95      get { return this.textFont; }
96      set {
97        this.textFont = value;
98        this.Repaint();
99      }
100    }
101
102    private ISymbolicExpressionTree tree;
103    public ISymbolicExpressionTree Tree {
104      get { return this.tree; }
105      set {
106        tree = value;
107        visualTreeNodes = new Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode>();
108        visualLines = new Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection>();
109        if (tree != null) {
110          foreach (ISymbolicExpressionTreeNode node in tree.IterateNodesPrefix()) {
111            visualTreeNodes[node] = new VisualSymbolicExpressionTreeNode(node);
112            if (node.Parent != null) visualLines[Tuple.Create(node.Parent, node)] = new VisualSymbolicExpressionTreeNodeConnection();
113          }
114        }
115        Repaint();
116      }
117    }
118
119    private bool suspendRepaint;
120    public bool SuspendRepaint {
121      get { return suspendRepaint; }
122      set { suspendRepaint = value; }
123    }
124    #endregion
125
126    protected override void OnPaint(PaintEventArgs e) {
127      e.Graphics.DrawImage(image, 0, 0);
128      base.OnPaint(e);
129    }
130    protected override void OnResize(EventArgs e) {
131      base.OnResize(e);
132      if (this.Width <= 1 || this.Height <= 1)
133        this.image = new Bitmap(1, 1);
134      else
135        this.image = new Bitmap(Width, Height);
136      this.Repaint();
137    }
138
139    public void Repaint() {
140      if (!suspendRepaint) {
141        this.GenerateImage();
142        this.Refresh();
143      }
144    }
145
146    public void RepaintNodes() {
147      if (!suspendRepaint) {
148        using (var graphics = Graphics.FromImage(image)) {
149          graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
150          graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
151          foreach (var visualNode in visualTreeNodes.Values) {
152            DrawTreeNode(graphics, visualNode);
153          }
154        }
155        this.Refresh();
156      }
157    }
158
159    public void RepaintNode(VisualSymbolicExpressionTreeNode visualNode) {
160      if (!suspendRepaint) {
161        using (var graphics = Graphics.FromImage(image)) {
162          graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
163          graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
164          DrawTreeNode(graphics, visualNode);
165        }
166        this.Refresh();
167      }
168    }
169
170    private void GenerateImage() {
171      using (Graphics graphics = Graphics.FromImage(image)) {
172        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
173        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
174        graphics.Clear(backgroundColor);
175        if (tree != null) {
176          DrawFunctionTree(tree, graphics, preferredNodeWidth, preferredNodeHeight, minHorizontalDistance, minVerticalDistance);
177        }
178      }
179    }
180
181    public VisualSymbolicExpressionTreeNode GetVisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode) {
182      if (visualTreeNodes.ContainsKey(symbolicExpressionTreeNode))
183        return visualTreeNodes[symbolicExpressionTreeNode];
184      return null;
185    }
186
187    public VisualSymbolicExpressionTreeNodeConnection GetVisualSymbolicExpressionTreeNodeConnection(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
188      if (child.Parent != parent) throw new ArgumentException();
189      var key = Tuple.Create(parent, child);
190      VisualSymbolicExpressionTreeNodeConnection connection = null;
191      visualLines.TryGetValue(key, out connection);
192      return connection;
193    }
194
195    #region events
196    public event MouseEventHandler SymbolicExpressionTreeNodeClicked;
197    protected virtual void OnSymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
198      var clicked = SymbolicExpressionTreeNodeClicked;
199      if (clicked != null)
200        clicked(sender, e);
201    }
202
203    protected virtual void SymbolicExpressionTreeChart_MouseClick(object sender, MouseEventArgs e) {
204      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
205      if (visualTreeNode != null) {
206        OnSymbolicExpressionTreeNodeClicked(visualTreeNode, e);
207      }
208    }
209
210    public event MouseEventHandler SymbolicExpressionTreeNodeDoubleClicked;
211    protected virtual void OnSymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
212      var doubleClicked = SymbolicExpressionTreeNodeDoubleClicked;
213      if (doubleClicked != null)
214        doubleClicked(sender, e);
215    }
216
217    protected virtual void SymbolicExpressionTreeChart_MouseDoubleClick(object sender, MouseEventArgs e) {
218      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
219      if (visualTreeNode != null)
220        OnSymbolicExpressionTreeNodeDoubleClicked(visualTreeNode, e);
221    }
222
223    public event ItemDragEventHandler SymbolicExpressionTreeNodeDrag;
224    protected virtual void OnSymbolicExpressionTreeNodeDragDrag(object sender, ItemDragEventArgs e) {
225      var dragged = SymbolicExpressionTreeNodeDrag;
226      if (dragged != null)
227        dragged(sender, e);
228    }
229
230    private VisualSymbolicExpressionTreeNode draggedSymbolicExpressionTree;
231    private MouseButtons dragButtons;
232    private void SymbolicExpressionTreeChart_MouseDown(object sender, MouseEventArgs e) {
233      this.dragButtons = e.Button;
234      this.draggedSymbolicExpressionTree = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
235    }
236    private void SymbolicExpressionTreeChart_MouseUp(object sender, MouseEventArgs e) {
237      this.draggedSymbolicExpressionTree = null;
238      this.dragButtons = MouseButtons.None;
239    }
240
241    private void SymbolicExpressionTreeChart_MouseMove(object sender, MouseEventArgs e) {
242      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
243      if (draggedSymbolicExpressionTree != null &&
244        draggedSymbolicExpressionTree != visualTreeNode) {
245        OnSymbolicExpressionTreeNodeDragDrag(draggedSymbolicExpressionTree, new ItemDragEventArgs(dragButtons, draggedSymbolicExpressionTree));
246        draggedSymbolicExpressionTree = null;
247      } else if (draggedSymbolicExpressionTree == null &&
248        visualTreeNode != null) {
249        string tooltipText = visualTreeNode.ToolTip;
250        if (this.toolTip.GetToolTip(this) != tooltipText)
251          this.toolTip.SetToolTip(this, tooltipText);
252
253      } else if (visualTreeNode == null)
254        this.toolTip.SetToolTip(this, "");
255    }
256
257    public VisualSymbolicExpressionTreeNode FindVisualSymbolicExpressionTreeNodeAt(int x, int y) {
258      foreach (var visualTreeNode in visualTreeNodes.Values) {
259        if (x >= visualTreeNode.X && x <= visualTreeNode.X + visualTreeNode.Width &&
260            y >= visualTreeNode.Y && y <= visualTreeNode.Y + visualTreeNode.Height)
261          return visualTreeNode;
262      }
263      return null;
264    }
265    #endregion
266
267    #region methods for painting the symbolic expression tree
268    private void DrawFunctionTree(ISymbolicExpressionTree symbolicExpressionTree, Graphics graphics, int preferredWidth, int preferredHeight, int minHDistance, int minVDistance) {
269      var layoutNodes = layoutAdapter.Convert(symbolicExpressionTree).ToList();
270      layoutEngine.Reset();
271      layoutEngine.Root = layoutNodes[0];
272      layoutEngine.AddNodes(layoutNodes);
273      layoutEngine.MinHorizontalSpacing = (preferredWidth + minHDistance);
274      layoutEngine.MinVerticalSpacing = (preferredHeight + minVDistance);
275      layoutEngine.CalculateLayout();
276      var bounds = layoutEngine.Bounds();
277
278      double verticalScalingFactor = 1.0;
279      double layoutHeight = (bounds.Height + preferredHeight);
280      if (this.Height < layoutHeight)
281        verticalScalingFactor = this.Height / layoutHeight;
282
283      double horizontalScalingFactor = 1.0;
284      double layoutWidth = (bounds.Width + preferredWidth);
285      if (this.Width < layoutWidth)
286        horizontalScalingFactor = this.Width / layoutWidth;
287
288      double horizontalOffset;
289      if (this.Width > layoutWidth)
290        horizontalOffset = (this.Width - layoutWidth) / 2.0;
291      else
292        horizontalOffset = preferredWidth / 2.0;
293
294      var levels = layoutNodes.GroupBy(n => n.Level, n => n).ToList();
295      for (int i = levels.Count - 1; i >= 0; --i) {
296        var nodes = levels[i].ToList();
297
298        double minSpacing = double.MaxValue;
299        if (nodes.Count > 1) {
300          for (int j = 1; j < nodes.Count() - 1; ++j) {
301            var distance = nodes[j].X - nodes[j - 1].X; // guaranteed to be > 0
302            if (minSpacing > distance) minSpacing = distance;
303          }
304        }
305        minSpacing *= horizontalScalingFactor;
306
307        int minWidth = (int)Math.Round(preferredWidth * horizontalScalingFactor);
308        int width = (int)Math.Min(minSpacing, preferredWidth) - 2; // leave some pixels so that node margins don't overlap
309
310        foreach (var layoutNode in nodes) {
311          var visualNode = visualTreeNodes[layoutNode.Content];
312          visualNode.Width = width;
313          visualNode.Height = (int)Math.Round(preferredHeight * verticalScalingFactor);
314          visualNode.X = (int)Math.Round((layoutNode.X + horizontalOffset) * horizontalScalingFactor + (minWidth - width) / 2.0);
315          visualNode.Y = (int)Math.Round(layoutNode.Y * verticalScalingFactor);
316          DrawTreeNode(graphics, visualNode);
317        }
318      }
319      // draw node connections
320      foreach (var visualNode in visualTreeNodes.Values) {
321        var node = visualNode.SymbolicExpressionTreeNode;
322        foreach (var subtree in node.Subtrees) {
323          var visualLine = GetVisualSymbolicExpressionTreeNodeConnection(node, subtree);
324          var visualSubtree = visualTreeNodes[subtree];
325          var origin = new Point(visualNode.X + visualNode.Width / 2, visualNode.Y + visualNode.Height);
326          var target = new Point(visualSubtree.X + visualSubtree.Width / 2, visualSubtree.Y);
327          graphics.Clip = new Region(new Rectangle(Math.Min(origin.X, target.X), origin.Y, Math.Max(origin.X, target.X), target.Y));
328          using (var linePen = new Pen(visualLine.LineColor)) {
329            linePen.DashStyle = visualLine.DashStyle;
330            graphics.DrawLine(linePen, origin, target);
331          }
332        }
333      }
334    }
335
336    protected void DrawTreeNode(VisualSymbolicExpressionTreeNode visualTreeNode) {
337      using (var graphics = Graphics.FromImage(image)) {
338        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
339        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
340        DrawTreeNode(graphics, visualTreeNode);
341      }
342    }
343
344    protected void DrawTreeNode(Graphics graphics, VisualSymbolicExpressionTreeNode visualTreeNode) {
345      graphics.Clip = new Region(new Rectangle(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width + 1, visualTreeNode.Height + 1));
346      graphics.Clear(backgroundColor);
347      var node = visualTreeNode.SymbolicExpressionTreeNode;
348      using (var textBrush = new SolidBrush(visualTreeNode.TextColor))
349      using (var nodeLinePen = new Pen(visualTreeNode.LineColor))
350      using (var nodeFillBrush = new SolidBrush(visualTreeNode.FillColor)) {
351        //draw terminal node
352        if (node.SubtreeCount == 0) {
353          graphics.FillRectangle(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
354          graphics.DrawRectangle(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
355        } else {
356          graphics.FillEllipse(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
357          graphics.DrawEllipse(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
358        }
359        //draw name of symbol
360        var text = node.ToString();
361        graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
362      }
363    }
364    #endregion
365    #region save image
366    private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
367      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
368        string filename = saveFileDialog.FileName.ToLower();
369        if (filename.EndsWith("bmp")) SaveImageAsBitmap(filename);
370        else if (filename.EndsWith("emf")) SaveImageAsEmf(filename);
371        else SaveImageAsBitmap(filename);
372      }
373    }
374
375    public void SaveImageAsBitmap(string filename) {
376      if (tree == null) return;
377      Image image = new Bitmap(Width, Height);
378      using (Graphics g = Graphics.FromImage(image)) {
379        DrawFunctionTree(tree, g, preferredNodeWidth, preferredNodeHeight, minHorizontalDistance, minVerticalDistance);
380      }
381      image.Save(filename);
382    }
383
384    public void SaveImageAsEmf(string filename) {
385      if (tree == null) return;
386      using (Graphics g = CreateGraphics()) {
387        using (Metafile file = new Metafile(filename, g.GetHdc())) {
388          using (Graphics emfFile = Graphics.FromImage(file)) {
389            DrawFunctionTree(tree, emfFile, preferredNodeWidth, preferredNodeHeight, minHorizontalDistance, minVerticalDistance);
390          }
391        }
392        g.ReleaseHdc();
393      }
394    }
395    #endregion
396    #region export pgf/tikz
397    private void exportLatexToolStripMenuItem_Click(object sender, EventArgs e) {
398      using (var dialog = new SaveFileDialog { Filter = "Tex (*.tex)|*.tex" }) {
399        if (dialog.ShowDialog() != DialogResult.OK) return;
400        string filename = dialog.FileName.ToLower();
401        var formatter = new SymbolicExpressionTreeLatexFormatter();
402        File.WriteAllText(filename, formatter.Format(Tree));
403      }
404    }
405    #endregion
406  }
407}
Note: See TracBrowser for help on using the repository browser.