Click here to Skip to main content
15,886,556 members
Articles / Programming Languages / C# 4.0

Grandiose projects 5. Audio support

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
3 Feb 2012CPOL8 min read 23.1K   2K   8  
Audio support for grandiose projects
��using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters;

using System.Runtime.Serialization.Formatters.Binary;

using System.Xml;

using System.Xml.Xsl;

using System.Resources;

using System.Collections;

using System.Reflection;

using System.Diagnostics;









using DiagramUI;

using DiagramUI.Operations;

using Diagram.UI.Factory;

using DiagramUI.Factory;

using DiagramUI.Interfaces;

using Diagram.UI.Interfaces;



using DiagramUI.Forms;



using DataPerformer;



using DataWarehouse;

using DataWarehouse.Interfaces;



using TestCategory;



using ResourceService;



using WeifenLuo.WinFormsUI.Docking;



using BasicEngineeringUIFactory;

using BasicEngineeringUIFactory.Interfaces;



using ToolBox;



using DataWarehouse.Forms;



using WindowsExtensions;





using DataPerformer.Interfaces;

using DataWarehouse.Advanced.Forms;



using DataPerformerUI.Interfaces;

using DataPerformerUI;











namespace BasicEngineeringUIFactory.Advanced.Forms

{

    public partial class FormMain : Form, IBlob, IErrorHandler, IProcess, IStartStop, 

        DataPerformerUI.Interfaces.IAnimationParameters, IStartAnimation

    {



        #region Fields

        private PanelDesktop active;

        ToolsDiagram tools;

        EngineeringUIFactory factory;

        DatabaseInterface data;

       // private string text;

        private FormContainerDesigner formContainer;



        private FormDatabaseTree formData;

        FormTools formTools;



        string fn = "";



        FormDockableTree formTree;



      private DockPanel dockManager;



        private FormDesktop desktop;



        private IApplicationCreator creator;





        Panel docPanel;



      private bool isChecked = true;





        TestCategory.Interfaces.ITest test = null;



        private ToolStripButton[] startStopPauseButtons;



        private bool paused = false;







        #endregion



        #region Ctor



        private FormMain()

        {

            InitializeComponent();

            StaticExtensionDataPerformerUI.StartAnimation = this;

            startStopPauseButtons = new ToolStripButton[] { toolStripButtonStart, toolStripButtonStop, toolStripButtonPause };



        }



        internal FormMain(IApplicationCreator creator)

            : this()

        {

            this.creator = creator;

            openFileDialogScn.Filter = creator.FileFilter;

            saveFileDialogScn.Filter = creator.FileFilter;

            if (creator.DatabaseCoordinator == null)

            {

                databaseToolStripMenuItem.Visible = false;

                savetodatabaseToolStripMenuItem.Visible = false;

                loadfromdatabaseToolStripMenuItem.Visible = false;

            }

            if (creator.Log != null)

            {

                toolStripButtonTest.Visible = true;

                Action close = () => { creator.Log.Flush(); creator.Log.Close(); };

                Application.ThreadExit += (object o, EventArgs e) => { close(); };



            }

             Text = creator.Text;

            // creator.

            creator.LoadResources();

            Dictionary<string, object>[] standardResources = Common.UI.Resources.Utils.ControlUtilites.Resources;

            if (DiagramUI.Utils.ControlUtilites.Resources == null)

            {

                DiagramUI.Utils.ControlUtilites.Resources =

                    standardResources;

            }

            StaticExtensionBasicEngineeringUIFactoryAdvanced.Prepare(creator.Resources);

            this.Icon = creator.Icon;

            Filename = creator.Filename;

            if (Filename == null)

            {

                Filename = "";

            }

            this.LoadControlResources();

            toolStripComboBoxCheckDetails.SelectedIndex = StaticExtensionBasicEngineering.CheckLevel;

            formTree = new FormDockableTree();

            formTree.OnHide += delegate()

            {

                StaticExtensionBasicEngineering.ShowTree = false;

                StaticExtensionBasicEngineering.Save();

            };

            SetSettings();

        }



 

       /* public FormMain(PureDesktopPeer edit)

            : this()

        {

            this.edit = edit;

            prepare();

        }*/



        #endregion



        #region IErrorHandler Members



        void IErrorHandler.ShowError(Exception exception, int errorLevel)

        {

            if (errorLevel == 0)

            {

                DiagramUI.Utils.ControlUtilites.ShowError(this, exception, StaticExtensionBasicEngineeringUIFactoryAdvanced.Resources);

            }

            else if (errorLevel < 10)

            {

                ShowMessage(exception.Message);

            }

        }



        void IErrorHandler.ShowMessage(string message)

        {

            ShowMessage(message);

        }



   



        #endregion



        #region IProcess Members



        void IProcess.Start()

        {

            try

            {

                IAnimationParameters p = StaticExtensionDataPerformerUI.AnimationParameters;

                object[] o = p.Parameters as object[];

                IStartStop ss = this;

                ss.Action(null, Diagram.UI.Interfaces.ActionType.Start);

                toolStripButtonStop.Enabled = true;

                creator.Start((double)o[0], (double)o[1], (int)o[2], (int)o[3], (int)o[4], active);

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

                //ShowError(ex);

            }

        }



        /// <summary>

        /// Pauses process

        /// </summary>

        void IProcess.Pause()

        {

            factory.PauseWorker();

            IStartStop ss = this;

            ss.Action(null, Diagram.UI.Interfaces.ActionType.Pause);

            Diagram.UI.Interfaces.ActionType.Pause.EnableDisableButtons(startStopPauseButtons);

        }



        /// <summary>

        /// Resumes process

        /// </summary>

        void IProcess.Resume()

        {

            IStartStop ss = this;

            ss.Action(null, Diagram.UI.Interfaces.ActionType.Resume);

  

            Diagram.UI.Interfaces.ActionType.Resume.EnableDisableButtons(startStopPauseButtons);

            factory.Resume();

        }



        /// <summary>

        /// Terminates process

        /// </summary>

        void IProcess.Terminate()

        {

            IStartStop ss = this;

            ss.Action(null, Diagram.UI.Interfaces.ActionType.Stop);

            paused = false;

            factory.StopWorker();

            Diagram.UI.Interfaces.ActionType.Stop.EnableDisableButtons(startStopPauseButtons);

            toolStripStatusLabelCurentTimeInd.Text = "";

         }



        /// <summary>

        /// Shows status of process

        /// </summary>

        /// <param name="status">Status</param>

        void IProcess.ShowStatus(double status)

        {

        }



        /// <summary>

        /// Time of start

        /// </summary>

        double IProcess.StartTime

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }



        /// <summary>

        /// Step

        /// </summary>

        double IProcess.Step

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }



        /// <summary>

        /// Number of steps

        /// </summary>

        int IProcess.Count

        {

            get

            {

                return 0;

            }

            set

            {

            }

        }





        #endregion



        #region IBlob Members



        byte[] IBlob.Bytes

        {

            get

            {

                MemoryStream stream = new MemoryStream();

                SaveAll(stream);

                /*TestCategory.Interfaces.ITestInterface ti = creator.TestInterface;

                if (ti != null)

                {

                    test = ti.Edit(test, active);

                }

                if (test != null)

                {

                    BinaryFormatter bf = new BinaryFormatter();

                    bf.Serialize(stream, test);

                }*/

                return stream.GetBuffer();



            }

            set

            {

                MemoryStream stream = new MemoryStream(value);

                LoadFromStream(stream, ".cfa");

           /*     TestCategory.Interfaces.ITestInterface ti = creator.TestInterface;

                if (ti != null)

                {

                    stream.CreateTestReport(ti);

                }*/

            }

        }

        string IBlob.Extention

        {

            get { return "cfa"; }

            set { }

        }



        #endregion



        #region IDesktopPostLoad Members



        void PostLoad(IDesktop desktop)

        {

            update();

            PanelDesktop pd = desktop as PanelDesktop;

            IEnumerable<object> coll = active.AllComponents;

            foreach (object o in coll)

            {

                if (o is IStartStopConsumer)

                {

                    IStartStopConsumer ssc = o as IStartStopConsumer;

                    ssc.StartStop = this;

                }

            }

        }



        #endregion



        #region IStartStop Members



        void IStartStop.Action(object type, Diagram.UI.Interfaces.ActionType actionType)

        {

            actionType.EnableDisableButtons(startStopPauseButtons);

            ActionPrivate(actionType);

        }



        #endregion



        #region IAnimationParameters Members



        object IAnimationParameters.Parameters

        {

            get

            {

                double[] d = ControlDouble;

                int[] i = ControlInt;

                return new object[] { d[0], d[1], i[0], i[1], i[2] };

            }

            set

            {

                throw new NotImplementedException();

            }

        }



        #endregion



        #region IStartAnimation Members



        void IStartAnimation.Start()

        {

            IProcess p = this;

            if (paused)

            {

                p.Resume();

                return;

            }

            StartDisable();

            p.Start();

        }



        #endregion



        #region LoadSave



        public bool SaveAll(Stream stream)

        {

            try

            {

                Check();

                active.SaveAll(stream);

                if (creator.TestInterface != null)

                {

                    test = creator.TestInterface.Edit(this.test, active);

                }

                if (test != null)

                {

                    BinaryFormatter bf = new BinaryFormatter();

                    bf.Serialize(stream, this.test);

                }

                isChecked = false;

                return true;

            }

            catch (Exception ex)

            {

                isChecked = false;

                ex.ShowError(1);

            }

            return false;

        }





        public bool LoadFromStream(Stream stream, string ext)

        {

            bool b = active.LoadFromStream(stream, PureDesktopPeer.Binders, ext, ".cfa");

            if (!b)

            {

                return false;

            }

            if (creator.TestInterface != null)

            {

                stream.Position = 0;

                stream.CreateTestReport(creator.TestInterface);

            }

            return true;

        }



        private void Check()

        {

            if (!isChecked)

            {

                isChecked = true;

                active.Check();

            }

        }



        #endregion



        #region Init



        protected void Prepare()

        {

            factory = creator.Factory as EngineeringUIFactory;

            factory.TimeIndication += (double time) =>

                {

                    this.InvokeIfNeeded(() => { toolStripStatusLabelCurentTimeInd.Text = time + ""; });

                };



                

            factory.CancelProcess += () => {this.InvokeIfNeeded(StopAll); };

            creator.ApplicationInitializer.InitializeApplication();

            if (creator.Log != null)

            {

                factory.ErrorHandler = new DiagramUI.ErrorHandlers.TextWriterErrorHandler(creator.Log);

            }

            else

            {

                factory.ErrorHandler = this;

            }

            ResourceService.Resources.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;

            Environment.CurrentDirectory = ResourceService.Resources.CurrentDirectory + "";

//            tools = new ToolsDiagram(factory);

            CommonOperations.CreateArrowControl(panelToolLeft, tools);

            ButtonWrapper.Add(creator.Buttons, tabControlControls, tools, new Size(25, 25), StaticExtensionBasicEngineeringUIFactoryAdvanced.Resources, true);

            ContainerPerformerUI.InitContainers(AppDomain.CurrentDomain.BaseDirectory, tools, tabControlControls,

                StaticExtensionBasicEngineeringUIFactoryAdvanced.Resources);



        }



        void StopAll()

        {

            StopEnable();

            IStartStop ss = this;

            ss.Action(null, Diagram.UI.Interfaces.ActionType.Stop);

        }



        private void initAll()

        {

            DataPerformer.StaticExtensionDataPerformerBase.Desktop = active;

            active.PostLoad += PostLoad;

            initTools();

            initContainers();

        }



        private void initTools()

        {

            EditorReceiver.AddEditorDrag(active);

            PictureReceiver.AddImageDrag(active);

        }







        private void initContainers()

        {

            Assembly ass = typeof(FormMain).Assembly;

            string path = Path.GetDirectoryName(ass.Location);

           // ContainerPerformerUI.InitContainers(path, tools, tabControlControls);

        }



        private void createDockMan()

        {

            if (dockManager == null)

            {

                dockManager = new DockPanel();

                  docPanel = this.panel1;

                //                dockManager.ActiveDocumentChanged += dockManager_ActiveDocumentChanged;

                this.dockManager.ActiveAutoHideContent = null;

                this.dockManager.Dock = System.Windows.Forms.DockStyle.Fill;

                this.dockManager.Location = new System.Drawing.Point(0, 28);

                this.dockManager.Name = "dockManager";

                this.dockManager.Size = new System.Drawing.Size(853, 600);

                this.dockManager.TabIndex = 1;

                docPanel.Controls.Add(dockManager);

                dockManager.DocumentStyle = DocumentStyle.DockingWindow;

                if (StaticExtensionBasicEngineering.LeftPortion > 0)

                {

                    dockManager.DockLeftPortion = StaticExtensionBasicEngineering.LeftPortion;

                    dockManager.DockRightPortion = StaticExtensionBasicEngineering.RightPortion;

                }

            

            }

        }









        #endregion



        #region Work with files





        private string Filename

        {

            get

            {

                return fn;

            }

            set

            {

                fn = value;

                string t = creator.Text.Localize();

                if (fn == null)

                {

                    Text = t;

                }

                else

                {

                    if (fn.Length > 0)

                    {

                        Text = t + " [" + Filename + "]";

                    }

                }

            }

        }



        private void SaveAs()

        {

            try

            {

                Check();

                saveFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";

                if (saveFileDialogScn.ShowDialog() != DialogResult.OK)

                {

                    return;

                }

                save(saveFileDialogScn.FileName);

                Filename = saveFileDialogScn.FileName;

            }

            catch (Exception ex)

            {

                ex.ShowError(1);

            }

        }



        private void save(string filename)

        {

            try

            {

                Check();

                Stream stream = File.Open(filename, FileMode.Create);

                SaveAll(stream);

                stream.Close();

            }

            catch (Exception ex)

            {

                ex.ShowError(1);

            }

        }





        private void save()

        {

            if (Filename == null)

            {

                SaveAs();

                return;

            }

            if (Filename.Length == 0)

            {

                SaveAs();

                return;

            }

           // check();

            save(Filename);

        }



  



        void LoadContainer(Stream stream)

        {

        }



        void Open()

        {

            //openFileDialogScn.InitialDirectory = ResourceService.Resources.CurrentDirectory + "scn";

            if (openFileDialogScn.ShowDialog(this) != DialogResult.OK)

            {

                return;

            }

            log(openFileDialogScn.FileName);

            string ext = Path.GetExtension(openFileDialogScn.FileName);

            Stream stream = File.OpenRead(openFileDialogScn.FileName);

         /*   if (ext.Equals("*.cont"))

            {

                LoadContainer(stream);

                return;

            }*/

            LoadFromStream(stream, ext);

            stream.Close();

            if (ext.ToLower().Equals(creator.Ext))

            {

                Filename = openFileDialogScn.FileName + "";

            }

            else

            {

                Filename = "";

            }

        }





        void log(string filename)

        {

            return;

          /*  string dir = AppDomain.CurrentDomain.BaseDirectory;

            if (dir[dir.Length - 1] != Path.DirectorySeparatorChar)

            {

                dir += Path.DirectorySeparatorChar;

            }

            StreamWriter wr = new StreamWriter(dir + "log.log", true, Encoding.UTF8);

            wr.WriteLine(filename);

            wr.WriteLine(DateTime.Now + "");

            wr.WriteLine("+++++++++++++++");

            Stream stream = File.OpenRead(filename);

            byte[] b = new byte[stream.Length];

            try

            {

                List<Exception> l = PureDesktopPeer.Check(b);

                if (l != null)

                {

                    foreach (Exception e in l)

                    {

                        wr.WriteLine(e.Message);

                        wr.WriteLine("------------");

                        wr.WriteLine(e.StackTrace);

                        wr.WriteLine("============");

                    }

                }

            }

            catch (Exception ex)

            {

                wr.WriteLine(ex.Message);

                wr.WriteLine("------------");

                wr.WriteLine(ex.StackTrace);

                wr.WriteLine("============");

            }

            wr.Flush();

            wr.Close();

            stream.Close();*/

        }





        #endregion



        #region Relicts



        #region Tests



        void testPerf()

        {

            /*   int n = 100;

               PureDesktopPeer d = new PureDesktopPeer();

               Stream stream = File.OpenRead(AppDomain.CurrentDomain.BaseDirectory +

                   "0.cfa");

               bool b = d.Load(stream, null);

               stream.Close();

               BitmapConsumer.IBitmapConsumer cons =

                   PureDesktop.GetAssociatedObject<BitmapConsumer.IBitmapConsumer>(d, "Picture map");

               StreamWriter wr = new StreamWriter("0.txt", false);

               DateTime t0 = DateTime.Now;

               wr.WriteLine(t0.ToLongTimeString());

               for (int i = 0; i < n; i++)

               {

                   cons.Process();

               }

               DateTime t1 = DateTime.Now;

               wr.WriteLine(t1.ToLongTimeString());

               TimeSpan dt = t1 - t0;

               double s = (60 * (double)dt.Minutes + (double)dt.Seconds + (double)dt.Milliseconds / 1000) / n;

               wr.WriteLine(s);

               wr.Close();*/

        }





 

        #endregion



        #region Sandcastle



        void setEnvProps(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("property");

            foreach (XmlElement e in l)

            {

                string name = e.Attributes["name"].Value;

                string value = e.Attributes["value"].Value;

                Environment.SetEnvironmentVariable(name, value, EnvironmentVariableTarget.User);

            }

        }



        string systemReplace(string str)

        {

            string s = str;

            while (true)

            {

                if (!s.Contains("$"))

                {

                    break;

                }

                int n = s.IndexOf('$');

                IDictionary d = Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User);

                foreach (object o in d.Keys)

                {

                    string ss = "${" + o + "}";

                    if (s.Contains(ss))

                    {

                        s = s.Replace(ss, d[o] + "");

                    }

                }

            }

            return s; ;

        }



        void copy(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("copy");

            foreach (XmlElement e in l)

            {

                copy(e);

            }

        }



        void copy(XmlElement e)

        {

            string inFile = systemReplace(e.Attributes["file"].Value);

            string outFile = systemReplace(e.Attributes["tofile"].Value);

            StreamReader r = new StreamReader(inFile);

            StreamWriter w = new StreamWriter(outFile);

            XmlNodeList l = e.GetElementsByTagName("replacestring");

            Dictionary<string, string> d = new Dictionary<string, string>();

            foreach (XmlElement el in l)

            {

                d[el.Attributes["from"].Value] = el.Attributes["to"].Value;

            }

            while (true)

            {

                string s = r.ReadLine();

                if (s == null)

                {

                    break;

                }

                foreach (string p in d.Keys)

                {

                    s = s.Replace(p, systemReplace(d[p]));

                }

                w.Write(s);

            }

            r.Close();

            w.Close();

        }





        private void exec(XmlDocument doc)

        {

            XmlNodeList l = doc.GetElementsByTagName("exec");

            exec(l[0] as XmlElement);

        }



        private void xmlToXsl(XmlDocument doc, string workDir)

        {

            string sxsl = "/xsl:";

            string sout = "/out:";



            XmlNodeList l = doc.GetElementsByTagName("arg");

            string[] s = new string[3];

            for (int i = 0; i < 3; i++)

            {

                int k = 0;



                string pref = null;

                XmlElement e = l[i] as XmlElement;

                string str = e.GetAttribute("value");

                if (str.Contains(sxsl))

                {

                    k = 1;

                    pref = sxsl;

                }

                if (str.Contains(sout))

                {

                    pref = sout;

                    k = 2;

                }

                if (pref != null)

                {

                    str = str.Substring(pref.Length);

                }

                str = systemReplace(str);

                if (str[0] == '\"' & str[str.Length - 1] == '\"')

                {

                    str = str.Substring(1, str.Length - 2);

                }

                if (File.Exists(workDir + str))

                {

                    str = workDir + str;

                }

                s[k] = str;

            }



            /*XslTransform xsl = new XslTransform();

            xsl.Load(s[1]);

            xsl.Transform(s[0], s[2]);*/



        }



        private void exec(XmlElement e)

        {

            string program = systemReplace(e.GetAttribute("program"));

            string workingDir = systemReplace(e.GetAttribute("workingdir"));

            string args = "";

            if (e.Attributes["commandline"] != null)

            {

                args = " " + e.GetAttribute("commandline");

            }

            XmlNodeList l = e.GetElementsByTagName("arg");

            foreach (XmlElement el in l)

            {

                string arg = systemReplace(el.GetAttribute("value"));

                args += " " + arg;

            }

            ProcessStartInfo info = new ProcessStartInfo(program, args);

            info.WorkingDirectory = workingDir;

            info.RedirectStandardOutput = true;

            info.RedirectStandardInput = true;

            info.RedirectStandardError = true;

            info.UseShellExecute = false;

            info.CreateNoWindow = true;

            Process p = new Process();

            p.StartInfo = info;

            p.Start();

            p.WaitForExit();

            StreamWriter wr = new StreamWriter("1.txt");

            while (true)

            {

                string s = p.StandardOutput.ReadLine();

                if (s == null)

                {

                    break;

                }

                wr.WriteLine(s);

            }

            wr.Close();

        }



        #endregion





        #endregion



        #region Event Handlers



        #region Open & Close Window



        private void FormMain_Load(object sender, EventArgs e)

        {

            if (creator.Holder != null)

            {

                // e

            }

            ShowDesktop();

            if (StaticExtensionBasicEngineering.ShowTools)

            {

                ShowTools();

            }

            if (StaticExtensionBasicEngineering.ShowTree)

            {

                ShowTree();

            }

            if (StaticExtensionBasicEngineering.ShowDatabase)

            {

                ShowData();

            }

            /* if (StaticExtension.ShowControl)

             {

                 ShowControl();

             }*/

            initAll();

            try

            {

                Prepare();

                ByteHolder holder = creator.Holder;

                if (holder != null)

                {

                    IDesktop edit = holder.Desktop;

                    active.Load(edit);

                }

                else

                {

                    byte[] b = StaticExtensionBasicEngineering.SavedState.StringToBytes();

                    MemoryStream ms = null;

                    if (b.Length > 1)

                    {

                        ms = new MemoryStream(b);

                    }

                    Stream stream = ms;

                    if (Filename != null)

                    {

                        if (Filename.Length != 0)

                        {

                            log(Filename);

                            stream = File.OpenRead(Filename);

                            // ext = Path.GetExtension(filename);

                        }

                    }

                    if (stream != null)

                    {

                        LoadFromStream(stream, creator.Ext);

                        stream.Close();

                    }

                }

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

            }

        }





        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)

        {

            if (!SaveSettings())

            {

                e.Cancel = true;

            }

        }



        #endregion



        #region Click Control Events



        private void clearallToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.RemoveAll();

            active.Redraw();

            active.Refresh();



        }



        private void clearselectedToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.RemoveSelected();

            active.Redraw();

            active.Refresh();



        }





        private void deletecommentsToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.DeleteComments();

        }





        private void toolStripButtonOpen_Click(object sender, EventArgs e)

        {

            openToolStripMenuItem_Click(sender, e);

        }





        private void toolStripButtonRefresh_Click(object sender, EventArgs e)

        {

            try

            {

                Check();

                active.RefreshObjects();

                //update();



                GC.Collect();

            }

            catch (Exception ex)

            {

                ex.ShowError(1);

            }

        }



        private void toolStripButtonFont_Click(object sender, EventArgs e)

        {

            try

            {

                TextBox box = ControlPanel.GetActiveTextBox(active);

                if (box == null)

                {

                    return;

                }

                FontDialog dlg = new FontDialog();

                dlg.ShowDialog(this);

                Font font = dlg.Font;

                box.Font = font;

            }

            catch (Exception ex)

            {

                ex.ShowError(1);

            }

        }



        private void toolStripButtonClear_Click(object sender, EventArgs e)

        {

            active.TempDelete();

        }





        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.SelectAll(true);

        }



        private void unselectAllToolStripMenuItem_Click(object sender, EventArgs e)

        {

            active.SelectAll(false);

        }



        private void toolStripButtonCut_Click(object sender, EventArgs e)

        {

            cutToolStripMenuItem_Click(sender, e);

        }



        private void toolStripButtonCopy_Click(object sender, EventArgs e)

        {

            copyToolStripMenuItem_Click(sender, e);

        }



        private void toolStripButtonPaste_Click(object sender, EventArgs e)

        {

            pasteToolStripMenuItem_Click(sender, e);

        }



        private void connectToolStripMenuItem_Click(object sender, EventArgs e)

        {

            StaticExtensionBasicEngineering.Server = "";

            data = null;

            prepareData();

        }



        private void toolStripButtonStart_Click(object sender, EventArgs e)

        {

            this.AnimationStart();

        }



        private void toolStripButtonStop_Click(object sender, EventArgs e)

        {

            Stop();

        }



        private void toolStripButtonPause_Click(object sender, EventArgs e)

        {

            Pause();

        }







        private void readWriteToolStripMenuItem_Click(object sender, EventArgs e)

        {

            if (!prepareData())

            {

                return;

            }

            FormDatabase form = new FormDatabase(

                new StandardStarter(ResourceService.Resources.CurrentDirectory + "Temp\\"),

                data, true);

            form.ShowDialog(this);



        }





        private void saveToolStripMenuItem_Click(object sender, EventArgs e)

        {

            if (Filename.Length == 0)

            {

                saveasToolStripMenuItem_Click(sender, e);

                return;

            }

            try

            {

                Stream stream = File.Open(Filename, FileMode.Create);

                SaveAll(stream);

                stream.Close();

            }

            catch (Exception ex)

            {

                ex.ShowError(1);

            }

        }



        private void loadfromdatabaseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            loadFromDatabase();

        }





        private void toolStripButtonLoadFromDatabase_Click(object sender, EventArgs e)

        {

            loadFromDatabase();

        }



        private void changeorderofselectedToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form form = new FormOrder(active);

            form.ShowDialog(this);



        }



        private void updateToolStripMenuItem_Click(object sender, EventArgs e)

        {

            update();

        }



        private void savetodatabaseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            SaveToDatabase();

        }



        private void openToolStripButton_Click(object sender, EventArgs e)

        {

           Open();

        }



        private void copyToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Stream stream = new MemoryStream();

            active.SaveSelected(stream);

            Clipboard.SetData("AstroFrame", stream);

        }



        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)

        {

            object o = Clipboard.GetData("AstroFrame");

            if (o == null)

            {

                return;

            }

            Stream stream = o as Stream;

            LoadFromStream(stream, creator.Ext);

        }



        private void cutToolStripMenuItem_Click(object sender, EventArgs e)

        {

            clearselectedToolStripMenuItem_Click(sender, e);

        }



        private void saveasToolStripMenuItem_Click(object sender, EventArgs e)

        {

            SaveAs();

        }



        private void openToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Open();

        }



        private void toolStripButtonStrict_Click(object sender, EventArgs e)

        {

            if (toolStripButtonStrict.Checked)

            {

                DiagramUI.StaticExtensionDiagramUI.SetStrictErrorHandler();

            }

            else

            {

                DiagramUI.StaticExtensionDiagramUI.ErrorHandler = null;

            }

        }



        private void browseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            if (folderBrowserDialog.ShowDialog(this) != DialogResult.OK)

            {

                return;

            }

            StaticExtensionBasicEngineering.SoundDirectory = folderBrowserDialog.SelectedPath;

            toolStripMenuItemSoundDirectory.Text = StaticExtensionBasicEngineering.SoundDirectory;

        }











        private void saveToolStripButton_Click(object sender, EventArgs e)

        {

            save();

        }



        private void derivationCalculatorToolStripMenuItem_Click(object sender, EventArgs e)

        {

            Form f = new DataPerformerUI.Forms.FormDerivationCalculator("xyzt");

            f.Show();

        }



        private void containerDesignerToolStripMenuItem_Click(object sender, EventArgs e)

        {

            showContainerDesigner();

        }



        private void toolStripButtonTest_Click(object sender, EventArgs e)

        {

            TestCategory.UI.TestPerformerUI perf = new TestCategory.UI.TestPerformerUI();

            perf.TestData(data, null, active, "cfa", "cfa", creator.Log);

            PureDesktopPeer d = new PureDesktopPeer();

            active.Copy(d);

            MemoryStream ms = new MemoryStream();

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(ms, d);

            MemoryStream str = new MemoryStream(ms.GetBuffer());

            d = bf.Deserialize(str) as PureDesktopPeer;

            clearallToolStripMenuItem_Click(null, null);

            active.Load(d);



        }

        private void toolStripButtonSync_Click(object sender, EventArgs e)

        {

            update();

        }



        private void dataToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowData();

        }



       /* private void controlToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowControl();

        }*/



        private void objectTreelBarToolStripMenuItemObjects_Click(object sender, EventArgs e)

        {

            ShowTree();

        }



        private void toolboxToolStripMenuItem_Click(object sender, EventArgs e)

        {

            ShowTools();

        }



        private void toolStripComboBoxCheckDetails_SelectedIndexChanged(object sender, EventArgs e)

        {

            SetCheckLevel();

        }





        #endregion



        #endregion



        #region Work with database



        private bool prepareData()

        {

            if (data != null)

            {

                return true;

            }

            string ser = "";

            try

            {

                ser = server;

                if (ser.Length == 0)

                {

                    connect();

                    if (server.Length == 0)

                    {

                        return false;

                    }

                    ser = server;

                }

                if (formData != null)

                {

                    formData.Hide();

                    formData = null;

                }

                IDatabaseInterface inter = //ReportingServer.ReportingInterface.GetService("");

                       DataWarehouse.DatabaseInterface.Coordinator[ser];



                IUser user = new User("", "", null);

                data = new DatabaseInterface(user, inter);

                ShowData();

                return true;

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

                if (StaticExtensionBasicEngineering.ConnectionStrings.Contains(ser))

                {

                    StaticExtensionBasicEngineering.ConnectionStrings.Remove(ser);

                }

                StaticExtensionBasicEngineering.Server = "";

                StaticExtensionBasicEngineering.Save();

                // loadfromdatabaseToolStripMenuItem.Visible = false;

                // savetodatabaseToolStripMenuItem.Visible = false;

                /*toolStripButtonLoadFromDatabase.Visible = false;

                databaseToolStripMenuItem.Visible = false;*/

            }

            return false;

        }





        private void connect()

        {

            /*

            FormConnectToDatabase form = new FormConnectToDatabase();

            form.ShowDialog(this);*/

            System.Collections.Specialized.StringCollection str = StaticExtensionBasicEngineering.ConnectionStrings;



            List<string> l = new List<string>();

            foreach (string s in str)

            {

                l.Add(s);

            }

            l.Sort();

            string serv = server + "";

            FormConnectionString form = new FormConnectionString(l, server);

            if (form.ShowDialog(this) != DialogResult.OK)

            {

                server = "";

                return;

            }

            serv = form.ConnectionString;

            if (!l.Contains(serv))

            {

                StaticExtensionBasicEngineering.ConnectionStrings.Add(serv);

                StaticExtensionBasicEngineering.Save();

            }

            server = serv;

        }



        private string server

        {

            get

            {



                // StaticExtension.Server = "3d-monstr";

                // StaticExtension.Save();

                string s = StaticExtensionBasicEngineering.Server;

                if (s.Length == 0)

                {

                    // dataToolStripMenuItem.Visible = false;

                }

                return StaticExtensionBasicEngineering.Server;

            }

            set

            {

                StaticExtensionBasicEngineering.Server = value;

                /*if (value.Length == 0)

                {

                    dataToolStripMenuItem.Visible = false;

                }

                else

                {

                    dataToolStripMenuItem.Visible = false;

                }*/

                StaticExtensionBasicEngineering.Save();

            }

        }







        void loadFromDatabase()

        {

            if (!prepareData())

            {

                return;

            }

            try

            {

                FormDatabase form = new FormDatabase(this, data, true);

                form.ShowDialog(this);

            }

            catch (Exception e)

            {

                e.ShowError(10);

                MessageBox.Show(e.Message);

            }

        }







        void SaveToDatabase()

        {

            if (!prepareData())

            {

                return;

            }

            FormDatabase form = new FormDatabase(this, data, false);

            

            form.ShowDialog(this);

        }



        #endregion



        #region Shows Child Windows



        private void showContainerDesigner()

        {



            DiagramUI.Forms.FormContainerDesigner.Show(active, ref formContainer);

        }



        private void AddSreamCreator(string name, PanelDesktop desktop)

        {

            Action<Stream> act = null;

            if (creator.TestInterface != null)

            {

                act = (Stream stream) => { stream.CreateTestReport(creator.TestInterface); };

            }

            desktop.AddStreamCreator(name, act);



        }





        private void ShowDesktop()

        {

            createDockMan();



            if (desktop == null)

            {

                tools = new ToolsDiagram(creator.Factory);

                desktop = new FormDesktop(tools, creator.Ext);

                AddSreamCreator("DataWarehouse.DatabaseStreamCreator", desktop.Desktop);

                tools.Tree = formTree.Tree;

            }

            desktop.Show(dockManager);

            active = desktop.Desktop;

            active.AllowDrop = true;

        }



        private void ShowTree()

        {

            createDockMan();

            formTree.Show(dockManager);

            StaticExtensionBasicEngineering.ShowTree = true;

            StaticExtensionBasicEngineering.Save();

        }



        private void ShowControl()

        {

            toolStripTextBoxStart.Text = StaticExtensionBasicEngineering.StartTime + "";

            toolStripTextBoxStep.Text = StaticExtensionBasicEngineering.Step + "";

            toolStripTextBoxPause.Text = StaticExtensionBasicEngineering.Pause + "";

            toolStripTextBoxStepCount.Text = StaticExtensionBasicEngineering.StepCount + "";

            toolStripTextBoxTimeIndicator.Text = StaticExtensionBasicEngineering.TimeIndicator + "";

            toolStripMenuItemSoundDirectory.Text = StaticExtensionBasicEngineering.SoundDirectory;

        }







        void ShowTools()

        {

            if (formTools == null)

            {

                formTools = new FormTools();

                DockContent c = formTools;

                formTools.OnHide += delegate()

                {

                    StaticExtensionBasicEngineering.ShowTools = false;

                    StaticExtensionBasicEngineering.Save();

                };

            }

            StaticExtensionBasicEngineering.ShowTools = true;

            StaticExtensionBasicEngineering.Save();

            formTools.Show(dockManager);

        }





        void ShowData()

        {

            if (creator.DatabaseCoordinator == null)

            {

                return;

            }

            createDockMan();

            if (formData == null)

            {

                if (data == null)

                {

                    try

                    {

                        string ser = server;

                        if (ser.Length == 0)

                        {

                            return;

                        }

                        IDatabaseInterface inter = //ReportingServer.ReportingInterface.GetService("");

                       DatabaseInterface.Coordinator[ser];



                        IUser user = new User("", "", null);

                        data = new DatabaseInterface(user, inter);

                        EngineeringUIFactory.Data = data;

                    }

                    catch (Exception ex)

                    {

                        ex.ShowError(10);

                        server = "";

                        return;

                    }

                }

                try

                {

                    formData = new FormDatabaseTree(data, creator.Ext, creator.Icon.ToBitmap());

                    formData.OnHide += delegate()

                    {

                        StaticExtensionBasicEngineering.ShowDatabase = false;

                        StaticExtensionBasicEngineering.Save();

                    };

                }

                catch (Exception exc)

                {

                    exc.ShowError(10);

                    MessageBox.Show(exc.Message);

                    StaticExtensionBasicEngineering.ShowDatabase = false;

                    StaticExtensionBasicEngineering.Save();

                    return;

                }

            }

            StaticExtensionBasicEngineering.ShowDatabase = true;

            StaticExtensionBasicEngineering.Save();

            formData.Show(dockManager);

        }





        #endregion



        #region Members



        #region Public Members



        public IApplicationCreator Creator

        {

            get

            {

                return creator;

            }

        }



  

        #endregion



        #region Nonpublic Members



        private void ShowMessage(string message)

        {

            StaticExtensionBasicEngineering.PlayError();

            toolStripStatusLabelError.Text = message;

        }



        private void ActionPrivate(Diagram.UI.Interfaces.ActionType actionType)

        {

            if (actionType == Diagram.UI.Interfaces.ActionType.Start)

            {

                StartDisable();

            }

            else

            {

                StopEnable();

            }

            StaticFactoryPerformer.Action(active, null, actionType);

            actionType.EnableDisableButtons(startStopPauseButtons);

        }





        

        void Stop()

        {

            StopEnable();

            IProcess p = this;

            p.Terminate();

            paused = false;

        }



        void Pause()

        {

            paused = true;

            IProcess p = this;

            p.Pause();

         }



        void StartDisable()

        {

            ToolStripItemCollection coll = toolStripMain.Items;

            foreach (ToolStripItem it in coll)

            {

                it.Enabled = false;

            }

            active.AllowDrop = false;

            menuStripMain.Enabled = false;

            tabControlControls.Enabled = false;

           // toolStripButtonStop.Enabled = true;

        }



        void StopEnable()

        {

            ToolStripItemCollection coll = toolStripMain.Items;

            foreach (ToolStripItem it in coll)

            {

                it.Enabled = true;

            }

            active.AllowDrop = true;

            menuStripMain.Enabled = true;

            tabControlControls.Enabled = true;

         }



        private void update()

        {

            try

            {

                using (TimeProviderBackup backup = new TimeProviderBackup(active, 0, null))

                {

                    IDataPerformerRuntime r = backup.Runtime;

                    r.Refresh();

                    r.StartAll(StartTime);

                    r.TimeProvider.Time = StartTime;

                    r.UpdateAll();

                }

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

                //ShowError(ex);

            }

        }



        void SetSettings()

        {

            WindowState = StaticExtensionBasicEngineering.FullScreen ? FormWindowState.Maximized : FormWindowState.Normal;

            Left = StaticExtensionBasicEngineering.Left = Left;

            Top = StaticExtensionBasicEngineering.Top = Top;

            if (StaticExtensionBasicEngineering.Width > 0)

            {

                Width = StaticExtensionBasicEngineering.Width;

                Height = StaticExtensionBasicEngineering.Height;

            }

            toolStripComboBoxCheckDetails.SelectedIndex = StaticExtensionBasicEngineering.CheckLevel;

            SetCheckLevel();

            toolStripComboBoxCheckDetails.SelectedIndexChanged += toolStripComboBoxCheckDetails_SelectedIndexChanged;

            ShowControl();

        }





        private double StartTime

        {

            get

            {

                return GetDouble(toolStripTextBoxStart, StaticExtensionBasicEngineering.StartTime);

            }

        }





        private double GetDouble(ToolStripTextBox tb, double def)

        {

            try

            {

                return Double.Parse(tb.Text);

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

            }

            return def;

        }

        

        private int GetInt(ToolStripTextBox tb, int def)

        {

            try

            {

                return Int32.Parse(tb.Text);

            }

            catch (Exception ex)

            {

                ex.ShowError(10);

            }

            return def;

        }



        private double[] GetDouble(ToolStripTextBox[] tb, double[] def)

        {

            double[] d = new double[tb.Length];

            for (int i = 0; i < d.Length; i++)

            {

                d[i] = GetDouble(tb[i], d[i]);

            }

            return d;

        }

        

        private int[] GetInt(ToolStripTextBox[] tb, int[] def)

        {

            int[] d = new int[tb.Length];

            for (int i = 0; i < d.Length; i++)

            {

                d[i] = GetInt(tb[i], d[i]);

            }

            return d;

        }





        double[] ControlDouble

        {

            get

            {

             double[] d = new double[]{StaticExtensionBasicEngineering.StartTime,

                StaticExtensionBasicEngineering.StartStep};

            double[] dx = GetDouble(new ToolStripTextBox[]

            {

                toolStripTextBoxStart,

                toolStripTextBoxStep

            }, d);

                return dx;

           }

        }





        int[] ControlInt

        {

            get

            {

                ToolStripTextBox[] tb = new ToolStripTextBox[]

      {

            toolStripTextBoxStepCount,

            toolStripTextBoxPause,

            toolStripTextBoxTimeIndicator

      };



                int[] i = new int[]

        {

           StaticExtensionBasicEngineering.StepCount,

          StaticExtensionBasicEngineering.Pause,

          StaticExtensionBasicEngineering.TimeIndicator

 



        };

                return GetInt(tb, i);

            }

        }









        bool SaveSettings()

        {

            GC.Collect();



            if (creator.Holder != null)

            {

                DialogResult dr = MessageBox.Show(

                    ResourceService.Resources.GetControlResource("Save data?", DiagramUI.Utils.ControlUtilites.Resources),

                    ResourceService.Resources.GetControlResource(creator.Text, DiagramUI.Utils.ControlUtilites.Resources),

                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                if (dr == DialogResult.Cancel)

                {

                    return false;

                }

                if (dr == DialogResult.No)

                {

                    return true;

                }



            }



            StaticExtensionBasicEngineering.FullScreen = (WindowState == FormWindowState.Maximized);

            StaticExtensionBasicEngineering.Left = Left;

            StaticExtensionBasicEngineering.Top = Top;

            StaticExtensionBasicEngineering.Width = Width;

            StaticExtensionBasicEngineering.Height = Height;

           if (dockManager != null)

            {

                //dockManager.Set.SetLayouot();

                StaticExtensionBasicEngineering.LeftPortion = dockManager.DockLeftPortion;

                StaticExtensionBasicEngineering.RightPortion = dockManager.DockRightPortion;

            }

            MemoryStream ms = new MemoryStream();

            if (!SaveAll(ms))

            {

                return false;

            }

            double[] d = ControlDouble;

            StaticExtensionBasicEngineering.StartTime = d[0];

            StaticExtensionBasicEngineering.Step = d[1];

            int[] ii = ControlInt;

            StaticExtensionBasicEngineering.StepCount = ii[0];

            StaticExtensionBasicEngineering.Pause = ii[1];

            StaticExtensionBasicEngineering.TimeIndicator = ii[2];

            if (creator.Holder == null)

            {

                byte[] b = ms.GetBuffer();

                StaticExtensionBasicEngineering.SavedState = b.BytesToString();

                StaticExtensionBasicEngineering.Save();

            }

            else

            {

                PureDesktopPeer edit = new PureDesktopPeer();

                active.Copy(edit);

                ByteHolder holder = new ByteHolder();

                holder.Bytes = edit.Content;

                creator.Holder = holder;

            }

            return true;

        }



        private void SetCheckLevel()

        {

            int i = toolStripComboBoxCheckDetails.SelectedIndex;

            if (i == 0)

            {

                DataPerformer.FormulaMeasure.CheckValue =

                    DataPerformer.FormulaMeasure.Check;

            }

            else

            {

                DataPerformer.FormulaMeasure.CheckValue =

                    DataPerformer.FormulaMeasure.EmptyCheck;

            }

            StaticExtensionBasicEngineering.CheckLevel = i;

            StaticExtensionBasicEngineering.Save();

        }



        #endregion



 

   

        #endregion



    }

}





By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Russian Federation Russian Federation
Ph. D. Petr Ivankov worked as scientific researcher at Russian Mission Control Centre since 1978 up to 2000. Now he is engaged by Aviation training simulators http://dinamika-avia.com/ . His additional interests are:

1) Noncommutative geometry

http://front.math.ucdavis.edu/author/P.Ivankov

2) Literary work (Russian only)

http://zhurnal.lib.ru/editors/3/3d_m/

3) Scientific articles
http://arxiv.org/find/all/1/au:+Ivankov_Petr/0/1/0/all/0/1

Comments and Discussions