Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1265: worked on visualization

  • added shortcut handling prototype
File size: 15.4 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            shortcut.DownAction();
232            break;
233          }
234        }
235      }
236    }
237
238    protected virtual void OnKeyUp(object sender, KeyEventArgs e) {
239      if (mode != null) {
240        mode.HandleOnKeyUp(sender, e);
241
242        if (e.Handled || ActiveShortcut == null) return;
243
244        var modifiers = new List<Keys>(from key in Enum.GetValues(typeof(Keys)).Cast<Keys>()
245                                       where e.Modifiers.HasFlag(key)
246                                       select key);
247
248        if (ActiveShortcut.Key == e.KeyCode || ActiveShortcut.GetModifiers().Except(modifiers).Any()) {
249          ActiveShortcut.UpAction();
250          ActiveShortcut = null;
251        }
252      }
253    }
254
255    protected virtual void PictureBoxOnMouseWheel(object sender, MouseEventArgs e) {
256      if (mode != null)
257        mode.HandleOnMouseWheel(sender, e);
258    }
259
260    protected virtual void PictureBoxOnMouseDown(object sender, MouseEventArgs e) {
261      if (mode != null)
262        mode.HandleOnMouseDown(sender, e);
263    }
264
265    protected virtual void PictureBoxOnMouseUp(object sender, MouseEventArgs e) {
266      if (mode != null)
267        mode.HandleOnMouseUp(sender, e);
268
269      if (Chart == null) return;
270
271      if (e.Button == MouseButtons.Right) {
272        propertiesToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
273        oneLayerUpToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
274        oneLayerDownToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
275        intoForegroundToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
276        intoBackgroundToolStripMenuItem.Enabled = Chart.Group.SelectedPrimitives.Count() == 1;
277      }
278    }
279
280    protected virtual void PictureBoxOnMouseMove(object sender, MouseEventArgs e) {
281      if (InvokeRequired) {
282        Invoke((Action<object, MouseEventArgs>)PictureBoxOnMouseMove, sender, e);
283      } else {
284        var toolTipText = Chart.GetToolTipText(e.Location);
285        if (toolTip.GetToolTip(pictureBox) != toolTipText) toolTip.SetToolTip(pictureBox, toolTipText);
286
287        if (mode != null)
288          mode.HandleOnMouseMove(sender, e);
289
290        SetPictureBoxCursor(GetPictureBoxCursor());
291      }
292    }
293
294    protected virtual void PictureBoxOnMouseEnter(object sender, EventArgs e) {
295      if (InvokeRequired) {
296        Invoke((Action<object, MouseEventArgs>)PictureBoxOnMouseEnter, sender, e);
297        return;
298      }
299      if (!Focused) pictureBox.Focus();
300
301      if (mode != null)
302        mode.HandleOnMouseEnter(sender, e);
303    }
304
305    protected virtual void PictureBoxOnMouseLeave(object sender, EventArgs e) {
306      if (mode != null)
307        mode.HandleOnMouseLeave(sender, e);
308    }
309
310    protected virtual void PictureBoxOnClick(object sender, EventArgs e) {
311      if (InvokeRequired) {
312        Invoke((Action<object, MouseEventArgs>)PictureBoxOnClick, sender, e);
313        return;
314      }
315      if (!Focused) pictureBox.Focus();
316
317      if (mode != null)
318        mode.HandleOnClick(sender, e);
319    }
320    #endregion
321
322    protected virtual void PictureBoxContextMenuStripOnOpening(object sender, CancelEventArgs e) { }
323
324    protected virtual void oneLayerUpToolStripMenuItem_Click(object sender, EventArgs e) {
325      if (Chart == null) return;
326      if (Chart.Group.SelectedPrimitives.Count() == 1) {
327        Chart.OneLayerUp(Chart.Group.SelectedPrimitives.First());
328      }
329    }
330    protected virtual void oneLayerDownToolStripMenuItem_Click(object sender, EventArgs e) {
331      if (Chart == null) return;
332      if (Chart.Group.SelectedPrimitives.Count() == 1) {
333        Chart.OneLayerDown(Chart.Group.SelectedPrimitives.First());
334      }
335    }
336    protected virtual void intoForegroundToolStripMenuItem_Click(object sender, EventArgs e) {
337      if (Chart == null) return;
338      if (Chart.Group.SelectedPrimitives.Count() == 1) {
339        Chart.IntoForeground(Chart.Group.SelectedPrimitives.First());
340      }
341    }
342    protected virtual void intoBackgroundToolStripMenuItem_Click(object sender, EventArgs e) {
343      if (Chart == null) return;
344      if (Chart.Group.SelectedPrimitives.Count() == 1) {
345        Chart.IntoBackground(Chart.Group.SelectedPrimitives.First());
346      }
347    }
348    protected virtual void propertiesToolStripMenuItem_Click(object sender, EventArgs e) {
349      if (Chart == null) return;
350      if (Chart.Group.SelectedPrimitives.Count() == 1) {
351        using (var dialog = new PropertiesDialog(Chart.Group.SelectedPrimitives.First())) {
352          dialog.ShowDialog(this);
353        }
354      }
355    }
356    protected virtual void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
357      if (Picture == null) return;
358
359      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
360        var format = ImageFormat.Bmp;
361        var filename = saveFileDialog.FileName.ToLower();
362        if (filename.EndsWith("emf")) {
363          using (var g1 = Graphics.FromImage(Picture)) {
364            var rectangle = new System.Drawing.Rectangle(0, 0, Picture.Width, Picture.Height);
365            using (var metafile = new Metafile(filename, g1.GetHdc(), rectangle, MetafileFrameUnit.Pixel, EmfType.EmfPlusDual))
366            using (var g2 = Graphics.FromImage(metafile))
367              Chart.Render(g2, pictureBox.Width, pictureBox.Height);
368          }
369        } else {
370          using (var graphics = Graphics.FromImage(Picture))
371            Chart.Render(graphics, Picture.Width, Picture.Height);
372
373          if (filename.EndsWith("jpg")) {
374            format = ImageFormat.Jpeg;
375          } else if (filename.EndsWith("gif")) {
376            format = ImageFormat.Gif;
377          } else if (filename.EndsWith("png")) {
378            format = ImageFormat.Png;
379          } else if (filename.EndsWith("tif")) {
380            format = ImageFormat.Tiff;
381          }
382
383          Picture.Save(saveFileDialog.FileName, format);
384        }
385      }
386    }
387
388    protected virtual void GenerateImage() {
389      if (InvokeRequired) {
390        Invoke((Action)GenerateImage);
391        return;
392      }
393      if (!Visible) {
394        RenderingRequired = true;
395      } else {
396        if ((pictureBox.Width == 0) || (pictureBox.Height == 0)) {
397          pictureBox.Image = pictureBox.ErrorImage;
398          if (Picture != null) Picture.Dispose();
399          Picture = null;
400        } else {
401          if (Picture != null) Picture.Dispose();
402          Picture = new Bitmap(pictureBox.Width, pictureBox.Height);
403          using (var graphics = Graphics.FromImage(Picture)) {
404            graphics.SmoothingMode = SmoothingMode;
405            graphics.SetClip(new System.Drawing.Rectangle(0, 0, pictureBox.Width, pictureBox.Height));
406            Chart.Render(graphics, pictureBox.Width, pictureBox.Height);
407          }
408        }
409        pictureBox.Image = Picture;
410        RenderingRequired = false;
411      }
412    }
413
414    public event EventHandler ModeChanged;
415    protected void OnModeChanged() {
416      var handler = ModeChanged;
417      if (handler != null) handler(this, EventArgs.Empty);
418    }
419
420    private void ChartControl_Load(object sender, EventArgs e) {
421      if (!SuppressRender) GenerateImage();
422    }
423
424    #region Helpers
425    private RadioButton CreateChartModeRadioButton(ChartMode chartMode) {
426      var rb = new RadioButton {
427        Appearance = Appearance.Button,
428        Image = chartMode.Image,
429        Size = new Size(24, 24),
430        TabStop = true,
431        Tag = chartMode,
432        UseVisualStyleBackColor = true
433      };
434
435      rb.CheckedChanged += (sender, args) => { if (rb.Checked) chartMode.Select(); };
436
437      return rb;
438    }
439
440    private ToolStripMenuItem CreateChartModeMenuItem(ChartMode chartMode) {
441      var mi = new ToolStripMenuItem(chartMode.Text) {
442        CheckOnClick = true,
443        Image = chartMode.Image,
444        Tag = chartMode
445      };
446
447      mi.CheckedChanged += (sender, args) => { if (mi.Checked) chartMode.Select(); };
448
449      return mi;
450    }
451    #endregion
452  }
453}
Note: See TracBrowser for help on using the repository browser.