Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.ExtLibs/HeuristicLab.Netron/3.0.2672.12446/Netron.Diagramming.Core-3.0.2672.12446/UI/DiagramControlBase.cs @ 2868

Last change on this file since 2868 was 2868, checked in by mkommend, 14 years ago

finished mapping from OperatorGraph to GraphVisualizationInfo (ticket #867)

File size: 34.8 KB
Line 
1using System;
2using System.IO;
3using System.Collections.Generic;
4using System.Text;
5using System.ComponentModel;
6using System.Windows.Forms;
7using System.Drawing;
8using System.Drawing.Printing;
9using System.Collections;
10namespace Netron.Diagramming.Core {
11  /// <summary>
12  /// Abstract base class for the various diagram control representations
13  /// (WebForm and WinForm).
14  /// </summary>
15  [ToolboxItem(false)]
16  public class DiagramControlBase :
17      ScrollableControl,
18      ISupportInitialize,
19      IDiagramControl {
20    #region Constants
21    protected const string constGeneral = "General";
22    #endregion
23
24    #region Events
25    /// <summary>
26    /// Occurs when the something got selected and the properties of it can/should be shown.
27    /// </summary>
28    [Category(constGeneral),
29    Description("Occurs when the something got selected and the " +
30        "properties of it can/should be shown."),
31    Browsable(true)]
32    public event EventHandler<SelectionEventArgs> OnShowSelectionProperties;
33    /// <summary>
34    /// Occurs when the Properties have changed
35    /// </summary>
36    [Category(constGeneral),
37    Description("Occurs when the properties have changed."),
38    Browsable(true)]
39    public event EventHandler<PropertiesEventArgs> OnShowDocumentProperties;
40    /// <summary>
41    /// Occurs when the properties of the canvas are exposed.
42    /// </summary>
43    public event EventHandler<SelectionEventArgs> OnShowCanvasProperties;
44    /// <summary>
45    /// Occurs when an entity is added.
46    /// <remarks>This event usually is bubbled from one of the layers</remarks>
47    /// </summary>
48    [Category(constGeneral), Description("Occurs when an entity is added."), Browsable(true)]
49    public event EventHandler<EntityEventArgs> OnEntityAdded;
50    /// <summary>
51    /// Occurs when an entity is removed.
52    /// <remarks>This event usually is bubbled from one of the layers</remarks>
53    /// </summary>
54    [Category(constGeneral), Description("Occurs when an entity is removed."), Browsable(true)]
55    public event EventHandler<EntityEventArgs> OnEntityRemoved;
56    /// <summary>
57    /// Occurs on opening a file
58    /// </summary>
59    [Category(constGeneral), Description("Occurs when the control will open a file."), Browsable(true)]
60    public event EventHandler<FileEventArgs> OnOpeningDiagram;
61    /// <summary>
62    /// Occurs when a file was opened
63    /// </summary>
64    [Category(constGeneral), Description(" Occurs when a file was opened."), Browsable(true)]
65    public event EventHandler<FileEventArgs> OnDiagramOpened;
66    /// <summary>
67    /// Occurs when the history has changed in the undo/redo mechanism
68    /// </summary>
69    public event EventHandler<HistoryChangeEventArgs> OnHistoryChange;
70    /// <summary>
71    /// Occurs before saving a diagram
72    /// </summary>
73    [Category(constGeneral), Description("Occurs before saving a diagram."), Browsable(true)]
74    public event EventHandler<FileEventArgs> OnSavingDiagram;
75    /// <summary>
76    /// Occurs after saving a diagram
77    /// </summary>
78    [Category(constGeneral), Description("Occurs after saving a diagram."), Browsable(true)]
79    public event EventHandler<FileEventArgs> OnDiagramSaved;
80    /// <summary>
81    /// Occurs when the control resets the document internally, usually through the Ctrl+N hotkey.
82    /// </summary>
83    [Category(constGeneral), Description("Occurs when the control resets the document internally, usually through the Ctrl+N hotkey."), Browsable(true)]
84    public event EventHandler OnNewDiagram;
85
86    #region Event raisers
87
88    /// <summary>
89    /// Raises the OnShowCanvasProperties event.
90    /// </summary>
91    protected void RaiseOnShowCanvasProperties(SelectionEventArgs e) {
92      EventHandler<SelectionEventArgs> handler = OnShowCanvasProperties;
93      if (handler != null) {
94        handler(this, e);
95      }
96    }
97    /// <summary>
98    /// Raises the OnNewDiagram event.
99    /// </summary>
100    protected void RaiseOnNewDiagram() {
101      EventHandler handler = OnNewDiagram;
102      if (handler != null) {
103        handler(this, EventArgs.Empty);
104      }
105    }
106    /// <summary>
107    /// Raises the OnHistory change.
108    /// </summary>
109    protected void RaiseOnHistoryChange(HistoryChangeEventArgs e) {
110      EventHandler<HistoryChangeEventArgs> handler = OnHistoryChange;
111      if (handler != null) {
112        handler(this, e);
113      }
114    }
115    /// <summary>
116    /// Raises the <see cref="OnShowDocumentProperties"/> event
117    /// </summary>
118    /// <param name="e">Properties event argument</param>
119    protected virtual void RaiseOnShowDocumentProperties(PropertiesEventArgs e) {
120      EventHandler<PropertiesEventArgs> handler = OnShowDocumentProperties;
121      if (handler != null) {
122        handler(this, e);
123      }
124    }
125    /// <summary>
126    /// Raises the OnSavingDiagram event
127    /// </summary>
128    /// <param name="filePath"></param>
129    public void RaiseOnSavingDiagram(string filePath) {
130      if (OnSavingDiagram != null)
131        OnSavingDiagram(this, new FileEventArgs(new System.IO.FileInfo(filePath)));
132    }
133    /// <summary>
134    /// Raises the OnShowSelectionProperties event.
135    /// </summary>
136    /// <param name="e">The <see cref="T:Netron.Diagramming.Core.SelectionEventArgs"/> instance containing the event data.</param>
137    protected virtual void RaiseOnShowSelectionProperties(SelectionEventArgs e) {
138      EventHandler<SelectionEventArgs> handler = OnShowSelectionProperties;
139      if (handler != null) {
140        handler(this, e);
141      }
142    }
143    /// <summary>
144    /// Raises the <see cref="OnEntityAdded"/> event.
145    /// </summary>
146    /// <param name="e">The <see cref="T:Netron.Diagramming.Core.EntityEventArgs"/> instance containing the event data.</param>
147    protected virtual void RaiseOnEntityAdded(EntityEventArgs e) {
148      EventHandler<EntityEventArgs> handler = OnEntityAdded;
149      if (handler != null) {
150        handler(this, e);
151      }
152    }
153    /// <summary>
154    /// Raises the <see cref="OnEntityRemoved"/>.
155    /// </summary>
156    /// <param name="e">The <see cref="T:Netron.Diagramming.Core.EntityEventArgs"/> instance containing the event data.</param>
157    protected virtual void RaiseOnEntityRemoved(EntityEventArgs e) {
158      EventHandler<EntityEventArgs> handler = OnEntityRemoved;
159      if (handler != null) {
160        handler(this, e);
161      }
162    }
163    /// <summary>
164    /// Raises the OnDiagramSaved event
165    /// </summary>
166    /// <param name="filePath"></param>
167    public void RaiseOnDiagramSaved(string filePath) {
168      if (OnDiagramSaved != null)
169        OnDiagramSaved(this, new FileEventArgs(new System.IO.FileInfo(filePath)));
170    }
171    /// <summary>
172    /// Raises the OnOpeningDiagram event
173    /// </summary>
174    public void RaiseOnOpeningDiagram(string filePath) {
175      if (OnOpeningDiagram != null)
176        OnOpeningDiagram(this, new FileEventArgs(new System.IO.FileInfo(filePath)));
177    }
178    /// <summary>
179    /// Raises the OnDiagramOpened event
180    /// </summary>
181    public void RaiseOnDiagramOpened(string filePath) {
182      if (OnDiagramOpened != null)
183        OnDiagramOpened(this, new FileEventArgs(new System.IO.FileInfo(filePath)));
184    }
185    #endregion
186
187
188    #endregion
189
190    #region Fields
191
192    // ------------------------------------------------------------------
193    /// <summary>
194    /// The page settings for printing the diagram.
195    /// </summary>
196    // ------------------------------------------------------------------
197    protected PageSettings mPageSettings;
198
199    // ------------------------------------------------------------------
200    /// <summary>
201    /// The filename to use when saving the diagram.
202    /// </summary>
203    // ------------------------------------------------------------------
204    protected string mFileName = "";
205
206    // ------------------------------------------------------------------
207    /// <summary>
208    /// Collection of files that were opened.  The collection can be
209    /// saved to disk by calling 'SaveRecentFiles(string path)'.
210    /// </summary>
211    // ------------------------------------------------------------------
212    protected ArrayList myRecentFiles = new ArrayList();
213
214    // ------------------------------------------------------------------
215    /// <summary>
216    /// the view
217    /// </summary>
218    // ------------------------------------------------------------------
219    protected IView mView;
220
221    // ------------------------------------------------------------------
222    /// <summary>
223    /// the controller
224    /// </summary>
225    // ------------------------------------------------------------------
226    protected IController mController;
227
228    // ------------------------------------------------------------------
229    /// <summary>
230    /// the Document field
231    /// </summary>
232    // ------------------------------------------------------------------
233    protected Document mDocument;
234    protected bool mEnableAddConnection = true;
235
236
237    #endregion
238
239    #region Properties
240
241    // ------------------------------------------------------------------
242    /// <summary>
243    /// Gets or sets the page settings for the entire document.
244    /// </summary>
245    // ------------------------------------------------------------------
246    public PageSettings PageSettings {
247      get {
248        return mPageSettings;
249      }
250      set {
251        mPageSettings = value;
252
253        // PageSettings has the page size in hundreths of an inch and
254        // the view requires mils (thousandths of an inch).
255        mView.PageSize = new Size(
256            mPageSettings.PaperSize.Width * 10,
257            mPageSettings.PaperSize.Height * 10);
258        mView.Landscape = mPageSettings.Landscape;
259      }
260    }
261
262    // ------------------------------------------------------------------
263    /// <summary>
264    /// Specifies if all shape's connectors are shown.
265    /// </summary>
266    // ------------------------------------------------------------------
267    public bool ShowConnectors {
268      get {
269        return this.mView.ShowConnectors;
270      }
271      set {
272        this.mView.ShowConnectors = value;
273      }
274    }
275
276    // ------------------------------------------------------------------
277    /// <summary>
278    /// Gets or sets the filename to save the diagram as.
279    /// </summary>
280    // ------------------------------------------------------------------
281    public string FileName {
282      get {
283        return mFileName;
284      }
285      set {
286        mFileName = value;
287      }
288    }
289
290    /// <summary>
291    /// Pans the diagram.
292    /// </summary>
293    /// <value>The pan.</value>
294    [Browsable(false)]
295    public Point Origin {
296      get { return this.Controller.View.Origin; }
297      set { this.Controller.View.Origin = value; }
298    }
299    /// <summary>
300    /// Gets or sets the magnification/zoom.
301    /// </summary>
302    /// <value>The magnification.</value>
303    [Browsable(false)]
304    public SizeF Magnification {
305      get { return this.Controller.View.Magnification; }
306      set { this.Controller.View.Magnification = value; }
307    }
308
309    /// <summary>
310    /// Gets the selected items.
311    /// </summary>
312    /// <value>The selected items.</value>
313    [Browsable(false)]
314    public CollectionBase<IDiagramEntity> SelectedItems {
315      get { return this.Controller.Model.Selection.SelectedItems; }
316    }
317
318    /// <summary>
319    /// Gets or sets whether to show the rulers.
320    /// </summary>
321    /// <value><c>true</c> to show the rulers; otherwise, <c>false</c>.</value>
322    [Browsable(true), Description("Gets or sets whether to show the rulers.")]
323    public bool ShowRulers {
324      get { return View.ShowRulers; }
325      set { View.ShowRulers = value; }
326    }
327
328    /// <summary>
329    /// Gets or sets whether a connection can be added.
330    /// </summary>
331    /// <value><c>true</c> if [enable add connection]; otherwise, <c>false</c>.</value>
332    [Browsable(true), Description("Gets or sets whether the user can add new connections to the diagram."), Category("Interactions")]
333    public bool EnableAddConnection {
334      get { return mEnableAddConnection; }
335      set { mEnableAddConnection = value; }
336    }
337
338    #endregion
339
340    #region Constructor
341    /// <summary>
342    /// Default constructor
343    /// </summary>
344    protected DiagramControlBase() {
345      // Update the display setting.
346      Graphics g = CreateGraphics();
347      Display.DpiX = g.DpiX;
348      Display.DpiY = g.DpiY;
349
350      //create the provider for all shapy diagram elements
351      ShapeProvider shapeProvider = new ShapeProvider();
352      TypeDescriptor.AddProvider(
353          shapeProvider,
354          typeof(SimpleShapeBase));
355
356      TypeDescriptor.AddProvider(
357          shapeProvider,
358          typeof(ComplexShapeBase));
359
360      //the provider for connections
361      ConnectionProvider connectionProvider =
362          new ConnectionProvider();
363
364      TypeDescriptor.AddProvider(
365          connectionProvider,
366          typeof(ConnectionBase));
367
368      //scrolling stuff
369      this.AutoScroll = true;
370      this.HScroll = true;
371      this.VScroll = true;
372
373      mPageSettings = new PageSettings();
374      mPageSettings.Landscape = true;
375      mPageSettings.PaperSize = new PaperSize("Letter", 850, 1100);
376    }
377    #endregion
378
379    #region Properties
380    /// <summary>
381    /// Gets or sets the background image displayed in the control.
382    /// </summary>
383    /// <value></value>
384    /// <returns>An <see cref="T:System.Drawing.Image"></see> that represents the image to display in the background of the control.</returns>
385    /// <PermissionSet><IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/></PermissionSet>
386    public override Image BackgroundImage {
387      get {
388        return base.BackgroundImage;
389      }
390      set {
391        base.BackgroundImage = value;
392        //TODO: change the backgroundtype
393      }
394    }
395    //protected override void OnGiveFeedback(GiveFeedbackEventArgs gfbevent)
396    //{
397    //    base.OnGiveFeedback(gfbevent);
398    //    gfbevent.UseDefaultCursors = false;
399    //    Cursor.Current = CursorPallet.DropShape;
400    //}
401    /// <summary>
402    ///
403    /// </summary>
404    [Browsable(true), Description("The background color of the canvas if the type is set to 'flat'"), Category("Appearance")]
405    public new Color BackColor {
406      get {
407
408        return base.BackColor;
409      }
410      set {
411        //communicate the change down to the model
412        //shouldn't this be done via the controller?
413        mDocument.Model.CurrentPage.Ambience.BackgroundColor = value;
414        ArtPalette.DefaultPageBackgroundColor = value;
415        base.BackColor = value;
416        this.Invalidate();
417      }
418    }
419    /// <summary>
420    /// Gets or sets the type of the background.
421    /// </summary>
422    /// <value>The type of the background.</value>
423    [Browsable(true), Description("The background type"), Category("Appearance"), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
424    public CanvasBackgroundTypes BackgroundType {
425      get { return mDocument.Model.CurrentPage.Ambience.BackgroundType; }
426      set { mDocument.Model.CurrentPage.Ambience.BackgroundType = value; }
427    }
428
429    /// <summary>
430    /// Gets or sets the view.
431    /// </summary>
432    /// <value>The view.</value>
433    public IView View {
434      get {
435        return mView;
436      }
437      set {
438        mView = value;
439      }
440    }
441
442    /// <summary>
443    /// Gets or sets the controller.
444    /// </summary>
445    /// <value>The controller.</value>
446    public IController Controller {
447      get {
448        return mController;
449      }
450      set { AttachToController(value); }
451
452    }
453
454    // ------------------------------------------------------------------
455    /// <summary>
456    /// Gets or sets the Document.  You must call
457    /// 'AttachToDocument(Document)' to apply a new document.
458    /// </summary>
459    // ------------------------------------------------------------------
460    public virtual Document Document {
461      get { return mDocument; }
462      set { mDocument = value; }
463    }
464
465
466    #endregion
467
468    #region Methods
469
470    // ------------------------------------------------------------------
471    /// <summary>
472    /// Saves all recently opened files to the path specified.  The files
473    /// are saved to a simple text file, one filename per line.
474    /// </summary>
475    /// <param name="path"></param>
476    /// <param name="maxFiles">int: The max number of filenams to
477    /// save.</param>
478    // ------------------------------------------------------------------
479    public virtual void SaveRecentlyOpenedFiles(
480        string path,
481        int maxFiles) {
482      if (myRecentFiles.Count < 1) {
483        return;
484      }
485
486      StreamWriter sw = File.CreateText(path);
487
488      // Keep track of all files saved so we don't save duplicates.
489      ArrayList savedFiles = new ArrayList();
490      string fileName;
491
492      // Start at the last (i.e. most recent file opened) and save
493      // until either 0 or maxFiles is reached.
494      for (int i = myRecentFiles.Count - 1; i >= 0; i--) {
495        if (maxFiles == 0) {
496          break;
497        }
498
499        fileName = myRecentFiles[i].ToString();
500        if (File.Exists(fileName)) {
501          if (savedFiles.Contains(fileName) == false) {
502            sw.WriteLine(fileName);
503            savedFiles.Add(fileName);
504            maxFiles--;
505          }
506        }
507      }
508      sw.Flush();
509      sw.Close();
510    }
511
512    // ------------------------------------------------------------------
513    /// <summary>
514    /// Reads the list of recently opened filenames from the
515    /// path specified.  If the path doesn't exist or if there aren't
516    /// any files to read, then 'null' is returned.
517    /// </summary>
518    /// <param name="path">string[]</param>
519    // ------------------------------------------------------------------
520    public virtual string[] ReadRecentlyOpenedFiles(string path) {
521      if (File.Exists(path) == false) {
522        return null;
523      }
524
525      StreamReader sr = new StreamReader(path);
526
527      string text = sr.ReadToEnd();
528      string[] filenames = text.Split("\n".ToCharArray());
529      this.myRecentFiles.Clear();
530      string trimmedFileName;
531      foreach (string filename in filenames) {
532        trimmedFileName = filename.Trim("\r".ToCharArray());
533        if (File.Exists(trimmedFileName)) {
534          this.myRecentFiles.Add(trimmedFileName);
535        }
536      }
537
538      if (this.myRecentFiles.Count > 0) {
539        return (string[])myRecentFiles.ToArray(typeof(string));
540      } else {
541        return null;
542      }
543    }
544
545    // ------------------------------------------------------------------
546    /// <summary>
547    /// Sets the layout root.
548    /// </summary>
549    /// <param name="shape">The shape.</param>
550    // ------------------------------------------------------------------
551    public virtual void SetLayoutRoot(IShape shape) {
552      this.Controller.Model.LayoutRoot = shape;
553    }
554
555    // ------------------------------------------------------------------
556    /// <summary>
557    /// Runs the activity.
558    /// </summary>
559    /// <param name="activityName">Name of the activity.</param>
560    // ------------------------------------------------------------------
561    public virtual void RunActivity(string activityName) {
562      this.Controller.RunActivity(activityName);
563    }
564
565    // ------------------------------------------------------------------
566    /// <summary>
567    /// Handles the OnEntityRemoved event of the Controller control.
568    /// </summary>
569    /// <param name="sender">The source of the event.</param>
570    /// <param name="e">The
571    /// <see cref="T:Netron.Diagramming.Core.EntityEventArgs"/> instance
572    /// containing the event data.</param>
573    // ------------------------------------------------------------------
574    protected virtual void HandleOnEntityRemoved(
575        object sender,
576        EntityEventArgs e) {
577      RaiseOnEntityRemoved(e);
578    }
579
580    // ------------------------------------------------------------------
581    /// <summary>
582    /// Handles the OnEntityAdded event of the Controller control.
583    /// </summary>
584    /// <param name="sender">The source of the event.</param>
585    /// <param name="e">The
586    /// <see cref="T:Netron.Diagramming.Core.EntityEventArgs"/> instance
587    /// containing the event data.</param>
588    // ------------------------------------------------------------------
589    protected virtual void HandleOnEntityAdded(
590        object sender,
591        EntityEventArgs e) {
592      RaiseOnEntityAdded(e);
593    }
594
595    // ------------------------------------------------------------------
596    /// <summary>
597    /// Handles the OnBackColorChange event of the View control.
598    /// </summary>
599    /// <param name="sender">The source of the event.</param>
600    /// <param name="e">The
601    /// <see cref="T:Netron.Diagramming.Core.ColorEventArgs"/> instance
602    /// containing the event data.</param>
603    // ------------------------------------------------------------------
604    protected void View_OnBackColorChange(object sender, ColorEventArgs e) {
605      base.BackColor = e.Color;
606    }
607
608    // ------------------------------------------------------------------
609    /// <summary>
610    /// Bubbles the OnHistoryChange event from the Controller to the surface
611    /// </summary>
612    /// <param name="sender">The source of the event.</param>
613    /// <param name="e">The
614    /// <see cref="T:Netron.Diagramming.Core.HistoryChangeEventArgs"/>
615    /// instance containing the event data.</param>
616    // ------------------------------------------------------------------
617    void mController_OnHistoryChange(
618        object sender,
619        HistoryChangeEventArgs e) {
620      RaiseOnHistoryChange(e);
621    }
622
623    void Controller_OnShowSelectionProperties(object sender, SelectionEventArgs e) {
624      RaiseOnShowSelectionProperties(e);
625    }
626
627    // ------------------------------------------------------------------
628    /// <summary>
629    /// Attaches to the controller specified and registers for all
630    /// required events to update this control from the controller.
631    /// </summary>
632    /// <param name="controller">IController</param>
633    // ------------------------------------------------------------------
634    protected virtual void AttachToController(IController controller) {
635
636      if (controller == null)
637        throw new ArgumentNullException();
638      mController = controller;
639      mController.OnHistoryChange +=
640          new EventHandler<HistoryChangeEventArgs>(
641          mController_OnHistoryChange);
642
643      mController.OnShowSelectionProperties +=
644          new EventHandler<SelectionEventArgs>(
645          Controller_OnShowSelectionProperties);
646
647      mController.OnEntityAdded +=
648          new EventHandler<EntityEventArgs>(
649          HandleOnEntityAdded);
650
651      mController.OnEntityRemoved +=
652          new EventHandler<EntityEventArgs>(
653          HandleOnEntityRemoved);
654    }
655
656    // ------------------------------------------------------------------
657    /// <summary>
658    /// Resets the document and underlying model.
659    /// </summary>
660    // ------------------------------------------------------------------
661    public virtual void NewDocument() {
662      // Lets see, we really only want to ask the user if they want to
663      // save their changes if they don't have changes to save.
664      // We can check the un/redo mananger to see if there are changes.
665      if ((this.mController.UndoManager.CanRedo()) ||
666          (this.mController.UndoManager.CanUndo())) {
667        DialogResult result = MessageBox.Show(
668            "Save changes before clearing the current diagram?",
669             "Confirm Clear",
670             MessageBoxButtons.YesNoCancel,
671             MessageBoxIcon.Question);
672
673        if (result == DialogResult.Yes) {
674          this.Save();
675        } else if (result == DialogResult.Cancel) {
676          return;
677        }
678      }
679      Document = new Document();
680      this.mController.UndoManager.ClearUndoRedo();
681      AttachToDocument(Document);
682      this.mFileName = "";
683      RaiseOnNewDiagram();
684      //this.Controller.Model.Clear();           
685    }
686
687    #region Printing
688
689    // ------------------------------------------------------------------
690    /// <summary>
691    /// Displays a PageSetupDialog so the user can specify how each
692    /// page is printed.
693    /// </summary>
694    // ------------------------------------------------------------------
695    public void PageSetup() {
696      PageSetupDialog dialog = new PageSetupDialog();
697      dialog.PageSettings = this.PageSettings;
698      if (dialog.ShowDialog() == DialogResult.OK) {
699        this.PageSettings = dialog.PageSettings;
700      }
701    }
702
703    // ------------------------------------------------------------------
704    /// <summary>
705    /// Prints all pages of the diagram.
706    /// </summary>
707    // ------------------------------------------------------------------
708    public void Print() {
709      DiagramPrinter myPrinter = new DiagramPrinter(
710          this.PageSettings,
711          this,
712          false);
713    }
714
715    // ------------------------------------------------------------------
716    /// <summary>
717    /// Print previews all pages of the diagram.
718    /// </summary>
719    // ------------------------------------------------------------------
720    public void PrintPreview() {
721      DiagramPrinter myPrinter = new DiagramPrinter(
722          this.PageSettings,
723          this,
724          true);
725    }
726
727    #endregion
728
729    #region IO
730    // ------------------------------------------------------------------
731    /// <summary>
732    /// If the current filename (FileName property) is empty, then a
733    /// SaveFileDialog is displayed for the user to specify what to save
734    /// the diagram as.  Otherwise, the current filename is used to save
735    /// the diagram.
736    /// </summary>
737    // ------------------------------------------------------------------
738    public virtual void Save() {
739      try {
740        if (this.mFileName == "") {
741          SaveFileDialog dialog = new SaveFileDialog();
742          if (dialog.ShowDialog() == DialogResult.OK) {
743            this.SaveAs(dialog.FileName);
744          }
745        } else {
746          this.SaveAs(this.mFileName);
747        }
748      }
749      catch (Exception ex) {
750        MessageBox.Show("An error occured while saving the " +
751            "diagram.  See below for the message about the " +
752            "error.\n\n" +
753            "Message: " + ex.Message,
754            "Save Diagram Error",
755            MessageBoxButtons.OK,
756            MessageBoxIcon.Error);
757      }
758    }
759
760    // ------------------------------------------------------------------
761    /// <summary>
762    /// Displays a SaveFileDialog regardless if there's an existing
763    /// filename so the user can save the diagram to a new location.
764    /// </summary>
765    // ------------------------------------------------------------------
766    public virtual void SaveAs() {
767      SaveFileDialog dialog = new SaveFileDialog();
768
769      if (dialog.ShowDialog() == DialogResult.OK) {
770        SaveAs(dialog.FileName);
771      }
772    }
773
774    // ------------------------------------------------------------------
775    /// <summary>
776    /// Saves the diagram to the given location.
777    /// </summary>
778    /// <param name="path">The path.</param>
779    // ------------------------------------------------------------------
780    public virtual void SaveAs(string path) {
781      if (!Directory.Exists(Path.GetDirectoryName(path))) {
782        throw new DirectoryNotFoundException(
783            "Create the directory before saving the diagram to it.");
784      }
785      RaiseOnSavingDiagram(path);
786      if (BinarySerializer.SaveAs(path, this) == true) {
787        // Store the filename if the save was successful.
788        this.mFileName = path;
789
790        // Clear the undo/redo history.
791        this.mController.UndoManager.ClearUndoRedo();
792        RaiseOnDiagramSaved(path);
793      }
794    }
795
796    // ------------------------------------------------------------------
797    /// <summary>
798    /// Displays an OpenFileDialog for the user to specify the diagram
799    /// to open.
800    /// </summary>
801    // ------------------------------------------------------------------
802    public virtual void Open() {
803      OpenFileDialog dialog = new OpenFileDialog();
804      if (dialog.ShowDialog() == DialogResult.OK) {
805        this.Open(dialog.FileName);
806      }
807    }
808
809    // ------------------------------------------------------------------
810    /// <summary>
811    /// Opens the diagram from the specified path.
812    /// </summary>
813    /// <param name="path">The path.</param>
814    // ------------------------------------------------------------------
815    public virtual void Open(string path) {
816      if (!Directory.Exists(Path.GetDirectoryName(path))) {
817        throw new DirectoryNotFoundException(
818            "Create the directory before saving the diagram to it.");
819      }
820      this.NewDocument();//makes it possible for the host to ask for
821      // saving first.
822
823      RaiseOnOpeningDiagram(path);//do it before opening the new diagram.
824      if (BinarySerializer.Open(path, this) == true) {
825        // Store the filename if successful.
826        this.mFileName = path;
827
828        // Add the filename to the list of previously opened files.
829        this.myRecentFiles.Add(path);
830
831        // Raise that a new diagram was opened.
832        RaiseOnDiagramOpened(path);
833      }
834      //this.mFileName = mFileName;
835    }
836    #endregion
837
838    // ------------------------------------------------------------------
839    /// <summary>
840    /// Attachement to the document.
841    /// </summary>
842    /// <param name="document">The document.</param>
843    // ------------------------------------------------------------------
844    public virtual void AttachToDocument(Document document) {
845
846      if (document == null)
847        throw new ArgumentNullException();
848
849      this.mDocument = document;
850
851      #region re-attach to the new model
852      View.Model = Document.Model;
853      Controller.Model = Document.Model;
854      #endregion
855      #region Update the ambience
856      document.Model.SetCurrentPage(0);
857      #endregion
858
859      this.Controller.Model.Selection.Clear();
860      this.Invalidate();
861    }
862
863    // ------------------------------------------------------------------
864    /// <summary>
865    /// Activates a registered tool with the given name
866    /// </summary>
867    /// <param name="toolName">the name of a tool</param>
868    // ------------------------------------------------------------------
869    [System.Diagnostics.CodeAnalysis.SuppressMessage(
870        "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")]
871    public void ActivateTool(string toolName) {
872      if (toolName == null || toolName.Trim().Length == 0) {
873        throw new ArgumentNullException("The tool name cannot " +
874            "be 'null' or empty.");
875      }
876
877      if (this.Controller == null) {
878        throw new InconsistencyException(
879            "The Controller of the surface is 'null', this is a " +
880            "strong inconsistency in the MVC model.");
881      }
882      if (toolName.Trim().Length > 0)
883        this.Controller.ActivateTool(toolName);
884    }
885
886    // ------------------------------------------------------------------
887    /// <summary>
888    /// Starts the tool with the given name.
889    /// </summary>
890    /// <param name="toolName">the name of a registered tool</param>
891    // ------------------------------------------------------------------
892    public void LaunchTool(string toolName) {
893      if (this.Controller == null) return;
894      this.Controller.ActivateTool(toolName);
895    }
896
897    // ------------------------------------------------------------------
898    /// <summary>
899    /// Overrides the base method to call the view which will paint the
900    /// diagram on the given graphics surface.
901    /// </summary>
902    /// <param name="e">PaintEventArgs</param>
903    // ------------------------------------------------------------------
904    protected override void OnPaint(PaintEventArgs e) {
905      base.OnPaint(e);
906      mView.Paint(e.Graphics);
907    }
908
909    // ------------------------------------------------------------------
910    /// <summary>
911    /// Paints the background of the control.
912    /// </summary>
913    /// <param name="pevent">A
914    /// <see cref="T:System.Windows.Forms.PaintEventArgs"></see> that
915    /// contains information about the control to paint.</param>
916    // ------------------------------------------------------------------
917    protected override void OnPaintBackground(PaintEventArgs pevent) {
918      base.OnPaintBackground(pevent);
919
920      mView.PaintBackground(pevent.Graphics);
921    }
922
923    // ------------------------------------------------------------------
924    /// <summary>
925    /// Undoes the last action that was recorded in the UndoManager.
926    /// </summary>
927    // ------------------------------------------------------------------
928    public void Undo() {
929      this.Controller.Undo();
930    }
931
932    // ------------------------------------------------------------------
933    /// <summary>
934    /// Redoes the last action that was recorded in the UndoManager.
935    /// </summary>
936    // ------------------------------------------------------------------
937    public void Redo() {
938      this.Controller.Redo();
939    }
940    #endregion
941
942    #region Explicit ISupportInitialize implementation
943    void ISupportInitialize.BeginInit() {
944      //here you can check the conformity of properties
945      BeginInit();
946    }
947
948    /// <summary>
949    /// Signals the object that initialization is complete.
950    /// </summary>
951    void ISupportInitialize.EndInit() {
952      EndInit();
953    }
954
955    /// <summary>
956    /// Signals the object that initialization is starting.
957    /// </summary>
958    protected virtual void BeginInit() {
959
960    }
961    /// <summary>
962    /// Signals the object that initialization is complete.
963    /// </summary>
964    protected virtual void EndInit() {
965      //necessary if the background type is gradient since the brush requires the size of the client rectangle
966      mView.SetBackgroundType(BackgroundType);
967
968      //the diagram control provider gives problems in design mode. If enable at design mode the
969      //diagramming control becomes a container component rather than a form control because the essential
970      //properties are disabled through the ControlProvider (the Location or ID for example).
971      //Also, do not try to put this in the constructor, you need the ISupportInitialize to get a meaningful DesignMode value.
972      if (!DesignMode) {
973        ControlProvider controlProvider = new ControlProvider();
974        TypeDescriptor.AddProvider(controlProvider, typeof(DiagramControlBase));
975      }
976    }
977    #endregion
978  }
979}
Note: See TracBrowser for help on using the repository browser.