Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Visualization/HeuristicLab.Visualization/3.3/ChartControl.cs @ 13763

Last change on this file since 13763 was 13763, checked in by jkarder, 8 years ago

#1265: worked on visualization

  • added null check for shortcut actions
File size: 15.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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.ComponentModel;
25using System.Drawing;
26using System.Drawing.Drawing2D;
27using System.Drawing.Imaging;
28using System.Linq;
29using System.Windows.Forms;
30
31namespace HeuristicLab.Visualization {
32  public partial class ChartControl : UserControl {
33    protected Bitmap Picture;
34    protected bool RenderingRequired;
35    protected Dictionary<Type, ChartMode> Modes = new Dictionary<Type, ChartMode>();
36    protected Stack<ChartMode> ModeStack = new Stack<ChartMode>();
37    protected List<ChartMode.Shortcut> Shortcuts = new List<ChartMode.Shortcut>();
38    protected ChartMode.Shortcut ActiveShortcut;
39
40    protected bool SuppressEvents { get; set; }
41    private bool SuppressRender { get; set; }
42
43    public bool ShowToolBar {
44      get { return !splitContainer.Panel1Collapsed; }
45      set { splitContainer.Panel1Collapsed = !value; }
46    }
47
48    private IChart chart;
49    public IChart Chart {
50      get { return chart; }
51      protected set {
52        if (chart != null) DeregisterChartEvents(chart);
53        chart = value;
54        chart.Enabled = Enabled;
55        pictureBox.Enabled = Enabled;
56        if (chart != null) RegisterChartEvents(chart);
57      }
58    }
59
60    private ChartMode mode;
61    private ChartMode defaultMode;
62    public ChartMode Mode {
63      get { return mode; }
64      set {
65        if (mode == value) return;
66        mode = value;
67        if (defaultMode == null) defaultMode = mode;
68        if (mode == null) mode = defaultMode;
69        SetModeButtonCheckedState();
70        SetModeMenuItemCheckedState();
71        SetPictureBoxCursor(GetPictureBoxCursor());
72        OnModeChanged();
73        if (chart != null) {
74          GenerateImage();
75        }
76      }
77    }
78
79    public SmoothingMode SmoothingMode { get; set; } = SmoothingMode.None;
80
81    public bool ScaleOnResize { get; set; }
82
83    public bool IsRenderingPaused { get { return SuppressRender; } }
84
85    public ChartControl() : this(null) { }
86    public ChartControl(IChart defaultChart) {
87      InitializeComponent();
88      ScaleOnResize = true;
89      Chart = defaultChart ?? new Chart(0, 0, Width, Height);
90    }
91
92    public void AddChartModes(params ChartMode[] chartModes) {
93      foreach (var chartMode in chartModes) {
94        Modes.Add(chartMode.GetType(), chartMode);
95        foreach (var shortcut in chartMode.Shortcuts)
96          Shortcuts.Add(shortcut);
97      }
98
99      ReloadModeToolBar();
100      ReloadModeContextMenu();
101    }
102
103    public void SetTempChartMode(ChartMode chartMode) {
104      if (Mode == chartMode) return;
105
106      ModeStack.Push(mode);
107      Mode = chartMode;
108    }
109
110    public void ResetTempChartMode() {
111      if (ModeStack.Any())
112        Mode = ModeStack.Pop();
113    }
114
115    public void SuspendRendering() {
116      SuppressRender = true;
117    }
118
119    public void ResumeRendering() {
120      SuppressRender = false;
121      if (Chart != null) GenerateImage();
122    }
123
124    public void RefreshPicture() {
125      pictureBox.Refresh();
126    }
127
128    public void UpdatePicture() {
129      pictureBox.Update();
130    }
131
132    public Graphics CreatePictureGraphics() {
133      return pictureBox.CreateGraphics();
134    }
135
136    protected virtual void ReloadModeToolBar() {
137      splitContainer.Panel1.Controls.Clear();
138
139      var chartModes = Modes.Values.ToList();
140      for (int i = 0; i < chartModes.Count; i++) {
141        var chartMode = chartModes[i];
142        var rb = CreateChartModeRadioButton(chartMode);
143        rb.Location = new Point(3, 3 + i * (rb.Height + rb.Margin.Vertical));
144        rb.TabIndex = i;
145        toolTip.SetToolTip(rb, chartMode.ToolTipText);
146        splitContainer.Panel1.Controls.Add(rb);
147      }
148
149      SetModeButtonCheckedState();
150    }
151
152    protected virtual void ReloadModeContextMenu() {
153      modeToolStripMenuItem.DropDownItems.Clear();
154
155      foreach (var chartMode in Modes.Values) {
156        var mi = CreateChartModeMenuItem(chartMode);
157        modeToolStripMenuItem.DropDownItems.Add(mi);
158      }
159
160      SetModeMenuItemCheckedState();
161    }
162
163    protected virtual void SetModeButtonCheckedState() {
164      foreach (var rb in splitContainer.Panel1.Controls.OfType<RadioButton>())
165        rb.Checked = rb.Tag == Mode;
166    }
167
168    protected virtual void SetModeMenuItemCheckedState() {
169      foreach (var mi in modeToolStripMenuItem.DropDownItems.OfType<ToolStripMenuItem>())
170        mi.Checked = mi.Tag == Mode;
171    }
172
173    protected virtual void SetPictureBoxCursor(Cursor cursor) {
174      if (pictureBox.Cursor != cursor) pictureBox.Cursor = cursor;
175    }
176
177    protected virtual Cursor GetPictureBoxCursor() {
178      return mode != null ? mode.Cursor : null;
179    }
180
181    protected virtual void RegisterChartEvents(IChart chart) {
182      chart.RedrawRequired += ChartOnUpdateRequired;
183    }
184
185    protected virtual void DeregisterChartEvents(IChart chart) {
186      chart.RedrawRequired -= ChartOnUpdateRequired;
187    }
188
189    protected virtual void ChartOnUpdateRequired(object sender, EventArgs e) {
190      if (SuppressRender) return;
191      GenerateImage();
192    }
193
194    #region PictureBox Events
195    protected virtual void PictureBoxOnSizeChanged(object sender, EventArgs e) {
196      if (Chart == null) return;
197      if (ScaleOnResize) {
198        if ((pictureBox.Width > 0) && (pictureBox.Height > 0) && (Chart != null)) {
199          var point = Chart.TransformPixelToWorld(new Point(pictureBox.Width, Chart.SizeInPixels.Height - pictureBox.Height));
200          var diff = Chart.UpperRight - point;
201          Chart.SetPosition(new PointD(Chart.LowerLeft.X + (diff.DX / 2.0), Chart.LowerLeft.Y + (diff.DY / 2.0)),
202            new PointD(Chart.UpperRight.X - (diff.DX / 2.0), Chart.UpperRight.Y - (diff.DY / 2.0)));
203        }
204      }
205      GenerateImage();
206    }
207
208    protected virtual void PictureBoxOnVisibleChanged(object sender, EventArgs e) {
209      if (pictureBox.Visible && RenderingRequired) GenerateImage();
210    }
211
212    protected virtual void PictureBoxOnMouseClick(object sender, MouseEventArgs e) {
213      if (mode != null)
214        mode.HandleOnMouseClick(sender, e);
215    }
216
217    protected virtual void PictureBoxOnMouseDoubleClick(object sender, MouseEventArgs e) {
218      if (mode != null)
219        mode.HandleOnMouseDoubleClick(sender, e);
220    }
221
222    protected virtual void OnKeyDown(object sender, KeyEventArgs e) {
223      if (mode != null) {
224        mode.HandleOnKeyDown(sender, e);
225
226        if (e.Handled || ActiveShortcut != null) return;
227
228        foreach (var shortcut in Shortcuts) {
229          if (e.KeyCode == shortcut.Key && e.Modifiers == shortcut.Modifiers) {
230            ActiveShortcut = shortcut;
231            var downAction = shortcut.DownAction;
232            if (downAction != null) downAction();
233            break;
234          }
235        }
236      }
237    }
238
239    protected virtual void OnKeyUp(object sender, KeyEventArgs e) {
240      if (mode != null) {
241        mode.HandleOnKeyUp(sender, e);
242
243        if (e.Handled || ActiveShortcut == null) return;
244
245        var modifiers = new List<Keys>(from key in Enum.GetValues(typeof(Keys)).Cast<Keys>()
246                                       where e.Modifiers.HasFlag(key)
247                                       select key);
248
249        if (ActiveShortcut.Key == e.KeyCode || ActiveShortcut.GetModifiers().Except(modifiers).Any()) {
250          var upAction = ActiveShortcut.UpAction;
251          if (upAction != null) upAction();
252          ActiveShortcut = null;
253        }
254      }
255    }
256
257    protected virtual void PictureBoxOnMouseWheel(object sender, MouseEventArgs e) {
258      if (mode != null)
259        mode.HandleOnMouseWheel(sender, e);
260    }
261
262    protected virtual void PictureBoxOnMouseDown(object sender, MouseEventArgs e) {
263      if (mode != null)
264        mode.HandleOnMouseDown(sender, e);
265    }
266
267    protected virtual void PictureBoxOnMouseUp(object sender, MouseEventArgs e) {
268      if (mode != null)
269        mode.HandleOnMouseUp(sender, e);
270
271      if (Chart == null) return;
272
273      if (e.Button == MouseButtons.Right) {
274        propertiesToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
275        oneLayerUpToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
276        oneLayerDownToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
277        intoForegroundToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
278        intoBackgroundToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
279      }
280    }
281
282    protected virtual void PictureBoxOnMouseMove(object sender, MouseEventArgs e) {
283      if (InvokeRequired) {
284        Invoke((Action<object, MouseEventArgs>)PictureBoxOnMouseMove, sender, e);
285      } else {
286        var toolTipText = Chart.GetToolTipText(e.Location);
287        if (toolTip.GetToolTip(pictureBox) != toolTipText) toolTip.SetToolTip(pictureBox, toolTipText);
288
289        if (mode != null)
290          mode.HandleOnMouseMove(sender, e);
291
292        SetPictureBoxCursor(GetPictureBoxCursor());
293      }
294    }
295
296    protected virtual void PictureBoxOnMouseEnter(object sender, EventArgs e) {
297      if (InvokeRequired) {
298        Invoke((Action<object, MouseEventArgs>)PictureBoxOnMouseEnter, sender, e);
299        return;
300      }
301      if (!Focused) pictureBox.Focus();
302
303      if (mode != null)
304        mode.HandleOnMouseEnter(sender, e);
305    }
306
307    protected virtual void PictureBoxOnMouseLeave(object sender, EventArgs e) {
308      if (mode != null)
309        mode.HandleOnMouseLeave(sender, e);
310    }
311
312    protected virtual void PictureBoxOnClick(object sender, EventArgs e) {
313      if (InvokeRequired) {
314        Invoke((Action<object, MouseEventArgs>)PictureBoxOnClick, sender, e);
315        return;
316      }
317      if (!Focused) pictureBox.Focus();
318
319      if (mode != null)
320        mode.HandleOnClick(sender, e);
321    }
322    #endregion
323
324    protected virtual void PictureBoxContextMenuStripOnOpening(object sender, CancelEventArgs e) { }
325
326    protected virtual void oneLayerUpToolStripMenuItem_Click(object sender, EventArgs e) {
327      if (Chart == null) return;
328      if (Chart.Group.SelectedPrimitives.Count() == 1) {
329        Chart.OneLayerUp(Chart.Group.SelectedPrimitives.First());
330      }
331    }
332    protected virtual void oneLayerDownToolStripMenuItem_Click(object sender, EventArgs e) {
333      if (Chart == null) return;
334      if (Chart.Group.SelectedPrimitives.Count() == 1) {
335        Chart.OneLayerDown(Chart.Group.SelectedPrimitives.First());
336      }
337    }
338    protected virtual void intoForegroundToolStripMenuItem_Click(object sender, EventArgs e) {
339      if (Chart == null) return;
340      if (Chart.Group.SelectedPrimitives.Count() == 1) {
341        Chart.IntoForeground(Chart.Group.SelectedPrimitives.First());
342      }
343    }
344    protected virtual void intoBackgroundToolStripMenuItem_Click(object sender, EventArgs e) {
345      if (Chart == null) return;
346      if (Chart.Group.SelectedPrimitives.Count() == 1) {
347        Chart.IntoBackground(Chart.Group.SelectedPrimitives.First());
348      }
349    }
350    protected virtual void propertiesToolStripMenuItem_Click(object sender, EventArgs e) {
351      if (Chart == null) return;
352      if (Chart.Group.SelectedPrimitives.Count() == 1) {
353        using (var dialog = new PropertiesDialog(Chart.Group.SelectedPrimitives.First())) {
354          dialog.ShowDialog(this);
355        }
356      }
357    }
358    protected virtual void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
359      if (Picture == null) return;
360
361      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
362        var format = ImageFormat.Bmp;
363        var filename = saveFileDialog.FileName.ToLower();
364        if (filename.EndsWith("emf")) {
365          using (var g1 = Graphics.FromImage(Picture)) {
366            var rectangle = new System.Drawing.Rectangle(0, 0, Picture.Width, Picture.Height);
367            using (var metafile = new Metafile(filename, g1.GetHdc(), rectangle, MetafileFrameUnit.Pixel, EmfType.EmfPlusDual))
368            using (var g2 = Graphics.FromImage(metafile))
369              Chart.Render(g2, pictureBox.Width, pictureBox.Height);
370          }
371        } else {
372          using (var graphics = Graphics.FromImage(Picture))
373            Chart.Render(graphics, Picture.Width, Picture.Height);
374
375          if (filename.EndsWith("jpg")) {
376            format = ImageFormat.Jpeg;
377          } else if (filename.EndsWith("gif")) {
378            format = ImageFormat.Gif;
379          } else if (filename.EndsWith("png")) {
380            format = ImageFormat.Png;
381          } else if (filename.EndsWith("tif")) {
382            format = ImageFormat.Tiff;
383          }
384
385          Picture.Save(saveFileDialog.FileName, format);
386        }
387      }
388    }
389
390    protected virtual void GenerateImage() {
391      if (InvokeRequired) {
392        Invoke((Action)GenerateImage);
393        return;
394      }
395      if (!Visible) {
396        RenderingRequired = true;
397      } else {
398        if ((pictureBox.Width == 0) || (pictureBox.Height == 0)) {
399          pictureBox.Image = pictureBox.ErrorImage;
400          if (Picture != null) Picture.Dispose();
401          Picture = null;
402        } else {
403          if (Picture != null) Picture.Dispose();
404          Picture = new Bitmap(pictureBox.Width, pictureBox.Height);
405          using (var graphics = Graphics.FromImage(Picture)) {
406            graphics.SmoothingMode = SmoothingMode;
407            graphics.SetClip(new System.Drawing.Rectangle(0, 0, pictureBox.Width, pictureBox.Height));
408            Chart.Render(graphics, pictureBox.Width, pictureBox.Height);
409          }
410        }
411        pictureBox.Image = Picture;
412        RenderingRequired = false;
413      }
414    }
415
416    public event EventHandler ModeChanged;
417    protected void OnModeChanged() {
418      var handler = ModeChanged;
419      if (handler != null) handler(this, EventArgs.Empty);
420    }
421
422    private void ChartControl_Load(object sender, EventArgs e) {
423      if (!SuppressRender) GenerateImage();
424    }
425
426    #region Helpers
427    private RadioButton CreateChartModeRadioButton(ChartMode chartMode) {
428      var rb = new RadioButton {
429        Appearance = Appearance.Button,
430        Image = chartMode.Image,
431        Size = new Size(24, 24),
432        TabStop = true,
433        Tag = chartMode,
434        UseVisualStyleBackColor = true
435      };
436
437      rb.CheckedChanged += (sender, args) => { if (rb.Checked) chartMode.Select(); };
438
439      return rb;
440    }
441
442    private ToolStripMenuItem CreateChartModeMenuItem(ChartMode chartMode) {
443      var mi = new ToolStripMenuItem(chartMode.Text) {
444        CheckOnClick = true,
445        Image = chartMode.Image,
446        Tag = chartMode
447      };
448
449      mi.CheckedChanged += (sender, args) => { if (mi.Checked) chartMode.Select(); };
450
451      return mi;
452    }
453    #endregion
454  }
455}
Note: See TracBrowser for help on using the repository browser.