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 @ 2768

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

added solution folders and sources for the netron library (ticket #867)

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