Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs @ 8942

Last change on this file since 8942 was 8942, checked in by mkommend, 12 years ago

#1763: Merged changes from TreeSimplifier branch to Encodings.symbolicExpressionTreeEncoding.Views.

File size: 14.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Windows.Forms;
27
28namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
29  public partial class SymbolicExpressionTreeChart : UserControl {
30    private Image image;
31    private StringFormat stringFormat;
32    private Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode> visualTreeNodes;
33    private Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection> visualLines;
34
35    public SymbolicExpressionTreeChart() {
36      InitializeComponent();
37      this.image = new Bitmap(Width, Height);
38      this.stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
39      this.spacing = 5;
40      this.lineColor = Color.Black;
41      this.backgroundColor = Color.White;
42      this.textFont = new Font("Times New Roman", 8);
43    }
44
45    public SymbolicExpressionTreeChart(ISymbolicExpressionTree tree)
46      : this() {
47      this.Tree = tree;
48    }
49
50    private int spacing;
51    public int Spacing {
52      get { return this.spacing; }
53      set {
54        this.spacing = value;
55        this.Repaint();
56      }
57    }
58
59    private Color lineColor;
60    public Color LineColor {
61      get { return this.lineColor; }
62      set {
63        this.lineColor = value;
64        this.Repaint();
65      }
66    }
67
68    private Color backgroundColor;
69    public Color BackgroundColor {
70      get { return this.backgroundColor; }
71      set {
72        this.backgroundColor = value;
73        this.Repaint();
74      }
75    }
76
77    private Font textFont;
78    public Font TextFont {
79      get { return this.textFont; }
80      set {
81        this.textFont = value;
82        this.Repaint();
83      }
84    }
85
86    private ISymbolicExpressionTree tree;
87    public ISymbolicExpressionTree Tree {
88      get { return this.tree; }
89      set {
90        tree = value;
91        visualTreeNodes = new Dictionary<ISymbolicExpressionTreeNode, VisualSymbolicExpressionTreeNode>();
92        visualLines = new Dictionary<Tuple<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode>, VisualSymbolicExpressionTreeNodeConnection>();
93        if (tree != null) {
94          foreach (ISymbolicExpressionTreeNode node in tree.IterateNodesPrefix()) {
95            visualTreeNodes[node] = new VisualSymbolicExpressionTreeNode(node);
96            if (node.Parent != null) visualLines[Tuple.Create(node.Parent, node)] = new VisualSymbolicExpressionTreeNodeConnection();
97          }
98        }
99        Repaint();
100      }
101    }
102
103    private bool suspendRepaint;
104    public bool SuspendRepaint {
105      get { return suspendRepaint; }
106      set { suspendRepaint = value; }
107    }
108
109    protected override void OnPaint(PaintEventArgs e) {
110      e.Graphics.DrawImage(image, 0, 0);
111      base.OnPaint(e);
112    }
113    protected override void OnResize(EventArgs e) {
114      base.OnResize(e);
115      if (this.Width <= 1 || this.Height <= 1)
116        this.image = new Bitmap(1, 1);
117      else
118        this.image = new Bitmap(Width, Height);
119      this.Repaint();
120    }
121
122    public void Repaint() {
123      if (!suspendRepaint) {
124        this.GenerateImage();
125        this.Refresh();
126      }
127    }
128
129    private void GenerateImage() {
130      using (Graphics graphics = Graphics.FromImage(image)) {
131        graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
132        graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
133        graphics.Clear(backgroundColor);
134        if (tree != null) {
135          int height = this.Height / tree.Depth;
136          DrawFunctionTree(tree, graphics, 0, 0, this.Width, height);
137        }
138      }
139    }
140
141    public VisualSymbolicExpressionTreeNode GetVisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode) {
142      if (visualTreeNodes.ContainsKey(symbolicExpressionTreeNode))
143        return visualTreeNodes[symbolicExpressionTreeNode];
144      return null;
145    }
146
147    public VisualSymbolicExpressionTreeNodeConnection GetVisualSymbolicExpressionTreeNodeConnection(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
148      if (child.Parent != parent) throw new ArgumentException();
149      var key = Tuple.Create(parent, child);
150      VisualSymbolicExpressionTreeNodeConnection connection = null;
151      visualLines.TryGetValue(key, out connection);
152      return connection;
153    }
154
155    #region events
156    public event MouseEventHandler SymbolicExpressionTreeNodeClicked;
157    protected virtual void OnSymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
158      var clicked = SymbolicExpressionTreeNodeClicked;
159      if (clicked != null)
160        clicked(sender, e);
161    }
162
163    private void SymbolicExpressionTreeChart_MouseClick(object sender, MouseEventArgs e) {
164      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
165      if (visualTreeNode != null) {
166        OnSymbolicExpressionTreeNodeClicked(visualTreeNode, e);
167      }
168    }
169
170    public event MouseEventHandler SymbolicExpressionTreeNodeDoubleClicked;
171    protected virtual void OnSymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
172      var doubleClicked = SymbolicExpressionTreeNodeDoubleClicked;
173      if (doubleClicked != null)
174        doubleClicked(sender, e);
175    }
176
177    private void SymbolicExpressionTreeChart_MouseDoubleClick(object sender, MouseEventArgs e) {
178      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
179      if (visualTreeNode != null)
180        OnSymbolicExpressionTreeNodeDoubleClicked(visualTreeNode, e);
181    }
182
183    public event ItemDragEventHandler SymbolicExpressionTreeNodeDrag;
184    protected virtual void OnSymbolicExpressionTreeNodeDragDrag(object sender, ItemDragEventArgs e) {
185      var dragged = SymbolicExpressionTreeNodeDrag;
186      if (dragged != null)
187        dragged(sender, e);
188    }
189
190    private VisualSymbolicExpressionTreeNode draggedSymbolicExpressionTree;
191    private MouseButtons dragButtons;
192    private void SymbolicExpressionTreeChart_MouseDown(object sender, MouseEventArgs e) {
193      this.dragButtons = e.Button;
194      this.draggedSymbolicExpressionTree = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
195    }
196    private void SymbolicExpressionTreeChart_MouseUp(object sender, MouseEventArgs e) {
197      this.draggedSymbolicExpressionTree = null;
198      this.dragButtons = MouseButtons.None;
199    }
200
201    private void SymbolicExpressionTreeChart_MouseMove(object sender, MouseEventArgs e) {
202      VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
203      if (draggedSymbolicExpressionTree != null &&
204        draggedSymbolicExpressionTree != visualTreeNode) {
205        OnSymbolicExpressionTreeNodeDragDrag(draggedSymbolicExpressionTree, new ItemDragEventArgs(dragButtons, draggedSymbolicExpressionTree));
206        draggedSymbolicExpressionTree = null;
207      } else if (draggedSymbolicExpressionTree == null &&
208        visualTreeNode != null) {
209        string tooltipText = visualTreeNode.ToolTip;
210        if (this.toolTip.GetToolTip(this) != tooltipText)
211          this.toolTip.SetToolTip(this, tooltipText);
212
213      } else if (visualTreeNode == null)
214        this.toolTip.SetToolTip(this, "");
215    }
216
217    public VisualSymbolicExpressionTreeNode FindVisualSymbolicExpressionTreeNodeAt(int x, int y) {
218      foreach (var visualTreeNode in visualTreeNodes.Values) {
219        if (x >= visualTreeNode.X && x <= visualTreeNode.X + visualTreeNode.Width &&
220            y >= visualTreeNode.Y && y <= visualTreeNode.Y + visualTreeNode.Height)
221          return visualTreeNode;
222      }
223      return null;
224    }
225    #endregion
226
227    #region methods for painting the symbolic expression tree
228    private void DrawFunctionTree(ISymbolicExpressionTree tree, Graphics graphics, int x, int y, int width, int height) {
229      DrawFunctionTree(tree.Root, graphics, x, y, width, height, Point.Empty);
230    }
231
232    /// <summary>
233    ///
234    /// </summary>
235    /// <param name="functionTree"> function tree to draw</param>
236    /// <param name="graphics">graphics object to draw on</param>
237    /// <param name="x">x coordinate of drawing area</param>
238    /// <param name="y">y coordinate of drawing area</param>
239    /// <param name="width">width of drawing area</param>
240    /// <param name="height">height of drawing area</param>
241    private void DrawFunctionTree(ISymbolicExpressionTreeNode node, Graphics graphics, int x, int y, int width, int height, Point connectionPoint) {
242      VisualSymbolicExpressionTreeNode visualTreeNode = visualTreeNodes[node];
243      float center_x = x + width / 2;
244      float center_y = y + height / 2;
245      int actualWidth = width - spacing;
246      int actualHeight = height - spacing;
247
248      SolidBrush textBrush = new SolidBrush(visualTreeNode.TextColor);
249      Pen nodeLinePen = new Pen(visualTreeNode.LineColor);
250      SolidBrush nodeFillBrush = new SolidBrush(visualTreeNode.FillColor);
251
252      //calculate size of node
253      if (actualWidth >= visualTreeNode.PreferredWidth && actualHeight >= visualTreeNode.PreferredHeight) {
254        visualTreeNode.Width = visualTreeNode.PreferredWidth;
255        visualTreeNode.Height = visualTreeNode.PreferredHeight;
256        visualTreeNode.X = (int)center_x - visualTreeNode.Width / 2;
257        visualTreeNode.Y = (int)center_y - visualTreeNode.Height / 2;
258      }
259        //width too small to draw in desired sized
260      else if (actualWidth < visualTreeNode.PreferredWidth && actualHeight >= visualTreeNode.PreferredHeight) {
261        visualTreeNode.Width = actualWidth;
262        visualTreeNode.Height = visualTreeNode.PreferredHeight;
263        visualTreeNode.X = x;
264        visualTreeNode.Y = (int)center_y - visualTreeNode.Height / 2;
265      }
266        //height too small to draw in desired sized
267      else if (actualWidth >= visualTreeNode.PreferredWidth && actualHeight < visualTreeNode.PreferredHeight) {
268        visualTreeNode.Width = visualTreeNode.PreferredWidth;
269        visualTreeNode.Height = actualHeight;
270        visualTreeNode.X = (int)center_x - visualTreeNode.Width / 2;
271        visualTreeNode.Y = y;
272      }
273        //width and height too small to draw in desired size
274      else {
275        visualTreeNode.Width = actualWidth;
276        visualTreeNode.Height = actualHeight;
277        visualTreeNode.X = x;
278        visualTreeNode.Y = y;
279      }
280
281      //draw terminal node
282      if (node.SubtreeCount == 0) {
283        graphics.FillRectangle(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
284        graphics.DrawRectangle(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
285      } else {
286        graphics.FillEllipse(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
287        graphics.DrawEllipse(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
288      }
289
290      //draw name of symbol
291      var text = node.ToString();
292      graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
293
294      //draw connection line to parent node
295      if (!connectionPoint.IsEmpty && node.Parent != null) {
296        var visualLine = GetVisualSymbolicExpressionTreeNodeConnection(node.Parent, node);
297        using (Pen linePen = new Pen(visualLine.LineColor)) {
298          linePen.DashStyle = visualLine.DashStyle;
299          graphics.DrawLine(linePen, connectionPoint, new Point(visualTreeNode.X + visualTreeNode.Width / 2, visualTreeNode.Y));
300        }
301      }
302
303      //calculate areas for the subtrees according to their tree size and call drawFunctionTree
304      Point connectFrom = new Point(visualTreeNode.X + visualTreeNode.Width / 2, visualTreeNode.Y + visualTreeNode.Height);
305      int[] xBoundaries = new int[node.SubtreeCount + 1];
306      xBoundaries[0] = x;
307      for (int i = 0; i < node.SubtreeCount; i++) {
308        xBoundaries[i + 1] = (int)(xBoundaries[i] + (width * (double)node.GetSubtree(i).GetLength()) / (node.GetLength() - 1));
309        DrawFunctionTree(node.GetSubtree(i), graphics, xBoundaries[i], y + height,
310          xBoundaries[i + 1] - xBoundaries[i], height, connectFrom);
311      }
312    }
313    #endregion
314
315    #region save image
316    private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
317      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
318        string filename = saveFileDialog.FileName.ToLower();
319        if (filename.EndsWith("bmp")) SaveImageAsBitmap(filename);
320        else if (filename.EndsWith("emf")) SaveImageAsEmf(filename);
321        else SaveImageAsBitmap(filename);
322      }
323    }
324
325    private void SaveImageAsBitmap(string filename) {
326      if (tree == null) return;
327      Image image = new Bitmap(Width, Height);
328      using (Graphics g = Graphics.FromImage(image)) {
329        int height = this.Height / tree.Depth;
330        DrawFunctionTree(tree, g, 0, 0, Width, height);
331      }
332      image.Save(filename);
333    }
334
335    private void SaveImageAsEmf(string filename) {
336      if (tree == null) return;
337      using (Graphics g = CreateGraphics()) {
338        using (Metafile file = new Metafile(filename, g.GetHdc())) {
339          using (Graphics emfFile = Graphics.FromImage(file)) {
340            int height = this.Height / tree.Depth;
341            DrawFunctionTree(tree, emfFile, 0, 0, Width, height);
342          }
343        }
344        g.ReleaseHdc();
345      }
346    }
347    #endregion
348  }
349}
Note: See TracBrowser for help on using the repository browser.