Free cookie consent management tool by TermsFeed Policy Generator

source: tags/3.3.8/HeuristicLab.ExtLibs/HeuristicLab.Netron/3.0.2672.12446/Netron.Diagramming.Core-3.0.2672.12446/UI/DiagramControlBase.cs @ 13398

Last change on this file since 13398 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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