Esempio n. 1
0
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("All molecule files (*.mol, *.sdf, *.cml)|*.mol;*.sdf;*.cml");
            sb.Append("|CML molecule files (*.cml)|*.cml");
            sb.Append("|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf");

            openFileDialog1.FileName = "*.*";
            openFileDialog1.Filter   = sb.ToString();

            DialogResult dr = openFileDialog1.ShowDialog();

            if (dr == DialogResult.OK)
            {
                string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower();
                string filename = Path.GetFileName(openFileDialog1.FileName);
                string mol      = File.ReadAllText(openFileDialog1.FileName);
                string cml      = "";

                CMLConverter    cmlConvertor    = new CMLConverter();
                SdFileConverter sdFileConverter = new SdFileConverter();
                Model           model           = null;

                switch (fileType)
                {
                case ".mol":
                case ".sdf":
                    model = sdFileConverter.Import(mol);
                    model.RefreshMolecules();
                    model.Relabel();
                    cml = cmlConvertor.Export(model);
                    //model.DumpModel("After Import");

                    break;

                case ".cml":
                case ".xml":
                    model = cmlConvertor.Import(mol);
                    model.RefreshMolecules();
                    model.Relabel();
                    cml = cmlConvertor.Export(model);
                    break;
                }

                this.Text = filename;
                this.display1.Chemistry = cml;
            }
        }
Esempio n. 2
0
        private void Redo_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Model m = _redoStack.Pop();
                Debug.WriteLine(
                    $"Popped F: {m.ConciseFormula} BL: {m.MeanBondLength.ToString("#,##0.00")} from Redo Stack");

                if (!string.IsNullOrEmpty(_lastCml))
                {
                    CMLConverter cc    = new CMLConverter();
                    var          clone = cc.Import(_lastCml);
                    _lastCml = cc.Export(m);

                    Debug.WriteLine(
                        $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Undo Stack");
                    _undoStack.Push(clone);
                }

                ShowChemistry($"Redo -> {m.ConciseFormula}", m);
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }
Esempio n. 3
0
        private void ExportAs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lastModel != null)
            {
                string result = string.Empty;

                switch (ExportAs.SelectedIndex)
                {
                case 1:
                    var cmlConverter = new CMLConverter();
                    result = cmlConverter.Export(lastModel);
                    break;

                case 2:
                    var sdFileConverter = new SdFileConverter();
                    result = sdFileConverter.Export(lastModel);
                    break;

                case 3:
                    var jsonConverter = new JSONConverter();
                    result = jsonConverter.Export(lastModel);
                    break;
                }

                if (!string.IsNullOrEmpty(result))
                {
                    //Clipboard.SetText(result);
                    //MessageBox.Show("Last loaded model exported to clipboard as CML");
                    textBox1.Text = result + Environment.NewLine;
                }
            }
            ExportAs.SelectedIndex = 0;
            LoadStructure.Focus();
        }
Esempio n. 4
0
        private void HandleChangedCml(string cml, string captionPrefix)
        {
            var cc = new CMLConverter();

            if (_lastCml != EmptyCml)
            {
                var clone = cc.Import(_lastCml);
                Debug.WriteLine(
                    $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                _undoStack.Push(clone);
            }

            Model m = cc.Import(cml);

            m.Relabel(true);
            m.EnsureBondLength(20, false);
            _lastCml = cc.Export(m);

            // Cause re-read of settings (in case they have changed)
            _editorOptions = new AcmeOptions(null);
            SetDisplayOptions();
            RedoStack.SetOptions(_editorOptions);
            UndoStack.SetOptions(_editorOptions);

            ShowChemistry($"{captionPrefix} {m.ConciseFormula}", m);
        }
Esempio n. 5
0
        private void OnWpfButtonClick(object sender, EventArgs e)
        {
            string       module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";
            WpfEventArgs args   = (WpfEventArgs)e;

            if (args.Button.ToUpper().Equals("OK"))
            {
                DialogResult = DialogResult.OK;
                CMLConverter  cc    = new CMLConverter();
                JSONConverter jc    = new JSONConverter();
                Model.Model   model = jc.Import(args.OutputValue);
                OutputValue = cc.Export(model);
            }

            if (args.Button.ToUpper().Equals("CANCEL"))
            {
                DialogResult = DialogResult.Cancel;
                OutputValue  = "";
            }

            WpfChemDoodle editor = elementHost1.Child as WpfChemDoodle;

            if (editor != null)
            {
                editor.OnButtonClick -= OnWpfButtonClick;
                editor = null;
            }
            Hide();
        }
Esempio n. 6
0
        private void ProcessResponse(HttpWebResponse response)
        {
            LabelInfo.Text = "";
            // read data via the response stream
            using (Stream resStream = response.GetResponseStream())
            {
                if (resStream != null)
                {
                    StreamReader sr   = new StreamReader(resStream);
                    string       temp = sr.ReadToEnd();

                    CMLConverter cmlConverter = new CMLConverter();
                    Model.Model  model        = cmlConverter.Import(temp);
                    if (model.MeanBondLength < Core.Helpers.Constants.MinimumBondLength - Core.Helpers.Constants.BondLengthTolerance ||
                        model.MeanBondLength > Core.Helpers.Constants.MaximumBondLength + Core.Helpers.Constants.BondLengthTolerance)
                    {
                        model.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                    }

                    Cml = cmlConverter.Export(model);

                    display1.Chemistry   = Cml;
                    ImportButton.Enabled = true;
                }
            }
        }
Esempio n. 7
0
        private void EditLabelsHost_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!_closedInCode)
            {
                if (elementHost1.Child is LabelsEditor editor)
                {
                    if (editor.IsDirty)
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("Do you wish to save your changes?");
                        sb.AppendLine("  Click 'Yes' to save your changes and exit.");
                        sb.AppendLine("  Click 'No' to discard your changes and exit.");
                        sb.AppendLine("  Click 'Cancel' to return to the form.");

                        DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                        switch (dr)
                        {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;

                        case DialogResult.Yes:
                            var cmlConvertor = new CMLConverter();
                            Cml          = cmlConvertor.Export(editor.EditedModel);
                            DialogResult = DialogResult.OK;
                            break;

                        case DialogResult.No:
                            DialogResult = DialogResult.Cancel;
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 8
0
        private void EditorHost_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != DialogResult.OK && e.CloseReason == CloseReason.UserClosing)
            {
                if (elementHost1.Child is CmlEditor editor &&
                    editor.IsDirty)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Do you wish to save your changes?");
                    sb.AppendLine("  Click 'Yes' to save your changes and exit.");
                    sb.AppendLine("  Click 'No' to discard your changes and exit.");
                    sb.AppendLine("  Click 'Cancel' to return to the form.");

                    DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                    switch (dr)
                    {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;

                    case DialogResult.Yes:
                        DialogResult = DialogResult.OK;
                        CMLConverter cc = new CMLConverter();
                        OutputValue = cc.Export(editor.EditedModel);
                        Hide();
                        break;

                    case DialogResult.No:
                        break;
                    }
                }
            }
        }
Esempio n. 9
0
        private void Save_Click(object sender, EventArgs e)
        {
            CMLConverter cc = new CMLConverter();

            DialogResult = DialogResult.Cancel;

            switch (_editorType)
            {
            case "ACME":
                if (elementHost1.Child is Editor acmeEditor &&
                    acmeEditor.IsDirty)
                {
                    DialogResult = DialogResult.OK;
                    var model = acmeEditor.EditedModel;
                    model.RescaleForCml();
                    // Replace any temporary Ids which are Guids
                    model.ReLabelGuids();
                    OutputValue = cc.Export(model);
                }
                break;

            case "LABELS":
                if (elementHost1.Child is LabelsEditor labelsEditor &&
                    labelsEditor.IsDirty)
                {
                    DialogResult = DialogResult.OK;
                    OutputValue  = cc.Export(labelsEditor.EditedModel);
                }
                break;

            default:
                if (elementHost1.Child is CmlEditor cmlEditor &&
                    cmlEditor.IsDirty)
                {
                    DialogResult = DialogResult.OK;
                    OutputValue  = cc.Export(cmlEditor.EditedModel);
                }
                break;
            }
            Hide();
        }
Esempio n. 10
0
        private void SaveStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                CMLConverter cmlConverter = new CMLConverter();
                Model        m            = cmlConverter.Import(_lastCml);
                m.CustomXmlPartGuid = "";

                string filter = "CML molecule files (*.cml, *.xml)|*.cml;*.xml|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf";
                using (SaveFileDialog sfd = new SaveFileDialog {
                    Filter = filter
                })
                {
                    DialogResult dr = sfd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        FileInfo fi = new FileInfo(sfd.FileName);
                        _telemetry.Write(module, "Information", $"Exporting to '{fi.Name}'");
                        string fileType = Path.GetExtension(sfd.FileName).ToLower();
                        switch (fileType)
                        {
                        case ".cml":
                        case ".xml":
                            string temp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                                          + Environment.NewLine
                                          + cmlConverter.Export(m);
                            File.WriteAllText(sfd.FileName, temp);
                            break;

                        case ".mol":
                        case ".sdf":
                            // https://www.chemaxon.com/marvin-archive/6.0.2/marvin/help/formats/mol-csmol-doc.html
                            double before = m.MeanBondLength;
                            // Set bond length to 1.54 angstroms (Å)
                            m.ScaleToAverageBondLength(1.54);
                            double after = m.MeanBondLength;
                            _telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                            SdFileConverter converter = new SdFileConverter();
                            File.WriteAllText(sfd.FileName, converter.Export(m));
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }
Esempio n. 11
0
 private void Save_Click(object sender, EventArgs e)
 {
     DialogResult  = DialogResult.OK;
     _closedInCode = true;
     if (elementHost1.Child is LabelsEditor editor)
     {
         CMLConverter cc = new CMLConverter();
         DialogResult = DialogResult.OK;
         Cml          = cc.Export(editor.EditedModel);
         Hide();
     }
 }
Esempio n. 12
0
        private void ImportStructure()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (_lastModel != null)
            {
                using (new WaitCursor())
                {
                    CMLConverter conv = new CMLConverter();

                    double before = _lastModel.MeanBondLength;
                    _lastModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                    double after = _lastModel.MeanBondLength;
                    Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    _lastModel.Relabel(true);
                    var expModel = _lastModel;

                    using (new WaitCursor())
                    {
                        if (expModel.Molecules.Values.Any())
                        {
                            var mol = expModel.Molecules.Values.First();

                            mol.Names.Clear();

                            if (_allResults.IupacNames != null)
                            {
                                foreach (var di in _allResults.IupacNames)
                                {
                                    var cn = new TextualProperty();
                                    cn.Value    = di.data;
                                    cn.FullType = "chebi:Iupac";
                                    mol.Names.Add(cn);
                                }
                            }

                            if (_allResults.Synonyms != null)
                            {
                                foreach (var di in _allResults.Synonyms)
                                {
                                    var cn = new TextualProperty();
                                    cn.Value    = di.data;
                                    cn.FullType = "chebi:Synonym";
                                    mol.Names.Add(cn);
                                }
                            }

                            Cml = conv.Export(expModel);
                        }
                    }
                }
            }
        }
Esempio n. 13
0
        // Called by ImportCml(), ImportCml()
        private long AddChemistry(SQLiteConnection conn, Model model, string chemistryName, string formula)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                long          lastId;
                StringBuilder sb = new StringBuilder();

                model.RemoveExplicitHydrogens();

                Byte[] blob = Encoding.UTF8.GetBytes(_cmlConverter.Export(model, true));
                //Byte[] blob = Encoding.UTF8.GetBytes(_sdFileConverter.Export(model));

                sb.AppendLine("INSERT INTO GALLERY");
                sb.AppendLine(" (Chemistry, Name, Formula)");
                sb.AppendLine("VALUES");
                sb.AppendLine(" (@blob, @name, @formula)");

                SQLiteCommand command = new SQLiteCommand(sb.ToString(), conn);
                command.Parameters.Add("@blob", DbType.Binary, blob.Length).Value          = blob;
                command.Parameters.Add("@name", DbType.String, chemistryName.Length).Value = chemistryName;
                command.Parameters.Add("@formula", DbType.String, formula.Length).Value    = formula;

                command.ExecuteNonQuery();
                string        sql = "SELECT last_insert_rowid()";
                SQLiteCommand cmd = new SQLiteCommand(sql, conn);
                lastId = (Int64)cmd.ExecuteScalar();

                return(lastId);
            }
            catch (Exception ex)
            {
                using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex))
                {
                    form.ShowDialog();
                }
                return(-1);
            }
        }
Esempio n. 14
0
 public void RefreshPanels()
 {
     RefreshFormulaePanel();
     RefreshNamesPanel();
     if (string.IsNullOrEmpty(_cml))
     {
         Model.Model model = new Model.Model();
         model.Molecules.Add(Molecule);
         CMLConverter cmlConverter = new CMLConverter();
         _cml = cmlConverter.Export(model);
         display1.Chemistry = _cml;
     }
 }
Esempio n. 15
0
        private void Save_Click(object sender, EventArgs e)
        {
            CMLConverter cc = new CMLConverter();

            DialogResult = DialogResult.Cancel;

            if (elementHost1.Child is CmlEditor editor &&
                editor.IsDirty)
            {
                DialogResult = DialogResult.OK;
                OutputValue  = cc.Export(editor.EditedModel);
            }
            Hide();
        }
Esempio n. 16
0
        public void CmlImportExportNested()
        {
            CMLConverter mc      = new CMLConverter();
            Model        model_1 = mc.Import(ResourceHelper.GetStringResource("NestedMolecules.xml"));

            // Basic Sanity Checks
            Assert.True(model_1.Molecules.Count == 1, $"Expected 1 Molecule; Got {model_1.Molecules.Count}");
            // Check molecule m0 has 4 child molecules and no atoms
            Molecule molecule_1 = model_1.Molecules.Values.First();

            Assert.True(molecule_1.Molecules.Count == 4, $"Expected 4 Molecule; Got {molecule_1.Molecules.Count}");
            Assert.True(molecule_1.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_1.Atoms.Count}");
            // Check molecule m2 has no child molecules and 6 atoms
            molecule_1 = model_1.Molecules.Values.First().Molecules.Values.ToList()[1];
            Assert.True(molecule_1.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_1.Molecules.Count}");
            Assert.True(molecule_1.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_1.Atoms.Count}");
            // Check molecule m1 has 1 child molecules and no atoms
            molecule_1 = model_1.Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule_1.Molecules.Count == 1, $"Expected 1 Molecule; Got {molecule_1.Molecules.Count}");
            Assert.True(molecule_1.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_1.Atoms.Count}");
            // Check molecule m5 has 1 child molecules and 6 atoms
            molecule_1 = model_1.Molecules.Values.First().Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule_1.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_1.Molecules.Count}");
            Assert.True(molecule_1.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_1.Atoms.Count}");

            var   exported = mc.Export(model_1);
            Model model_2  = mc.Import(exported);

            // Basic Sanity Checks
            Assert.True(model_2.Molecules.Count == 1, $"Expected 1 Molecule; Got {model_2.Molecules.Count}");
            // Check molecule m0 has 4 child molecules and no atoms
            Molecule molecule_2 = model_2.Molecules.Values.First();

            Assert.True(molecule_2.Molecules.Count == 4, $"Expected 4 Molecule; Got {molecule_2.Molecules.Count}");
            Assert.True(molecule_2.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_2.Atoms.Count}");
            // Check molecule m2 has no child molecules and 6 atoms
            molecule_2 = model_2.Molecules.Values.First().Molecules.Values.ToList()[1];
            Assert.True(molecule_2.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_2.Molecules.Count}");
            Assert.True(molecule_2.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_2.Atoms.Count}");
            // Check molecule m1 has 1 child molecules and no atoms
            molecule_2 = model_2.Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule_2.Molecules.Count == 1, $"Expected 1 Molecule; Got {molecule_2.Molecules.Count}");
            Assert.True(molecule_2.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_2.Atoms.Count}");
            // Check molecule m5 has 1 child molecules and 6 atoms
            molecule_2 = model_2.Molecules.Values.First().Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule_2.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_2.Molecules.Count}");
            Assert.True(molecule_2.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_2.Atoms.Count}");
        }
Esempio n. 17
0
        private void EditWithAcme_Click(object sender, EventArgs e)
        {
#if !DEBUG
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";
            try
            {
#endif
            if (!string.IsNullOrEmpty(_lastCml))
            {
                using (EditorHost editorHost = new EditorHost(_lastCml, "ACME"))
                {
                    editorHost.ShowDialog(this);
                    if (editorHost.DialogResult == DialogResult.OK)
                    {
                        CMLConverter cc    = new CMLConverter();
                        var          clone = cc.Import(_lastCml);
                        Debug.WriteLine(
                            $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                        _undoStack.Push(clone);

                        Model m = cc.Import(editorHost.OutputValue);
                        m.Relabel(true);
                        _lastCml = cc.Export(m);

                        // Cause re-read of settings (in case they have changed)
                        _editorOptions = new AcmeOptions(null);
                        SetDisplayOptions();
                        RedoStack.SetOptions(_editorOptions);
                        UndoStack.SetOptions(_editorOptions);

                        ShowChemistry($"Edited {m.ConciseFormula}", m);
                    }
                }
                TopMost = true;
                TopMost = false;
                Activate();
            }
#if !DEBUG
        }

        catch (Exception exception)
        {
            _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
            _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
            MessageBox.Show(exception.StackTrace, exception.Message);
        }
#endif
        }
Esempio n. 18
0
        private void Save_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            CMLConverter cc = new CMLConverter();

            DialogResult = DialogResult.Cancel;

            if (elementHost1.Child is Chem4Word.ACME.Editor editor &&
                editor.IsDirty)
            {
                DialogResult = DialogResult.OK;
                OutputValue  = cc.Export(editor.EditedModel);
            }
            Telemetry.Write(module, "Verbose", $"Result: {DialogResult}");
            Hide();
        }
Esempio n. 19
0
        public DialogResult Edit()
        {
            string       module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";
            DialogResult result = DialogResult.Cancel;

            try
            {
                Telemetry.Write(module, "Verbose", "Called");
                if (HasSettings)
                {
                    LoadSettings();
                }

                CMLConverter  cmlConverter  = new CMLConverter();
                Model.Model   model         = cmlConverter.Import(Cml);
                JSONConverter jsonConverter = new JSONConverter();
                string        json          = jsonConverter.Export(model);

                ChemDoodleWeb cdwEditor = new ChemDoodleWeb();
                cdwEditor.TopLeft            = TopLeft;
                cdwEditor.Telemetry          = Telemetry;
                cdwEditor.ProductAppDataPath = ProductAppDataPath;
                cdwEditor.UserOptions        = _editorOptions;
                cdwEditor.Before_JSON        = json;
                cdwEditor.IsSingleMolecule   = model.Molecules.Count == 1;
                cdwEditor.AverageBondLength  = model.MeanBondLength;

                result = cdwEditor.ShowDialog();
                if (result == DialogResult.OK)
                {
                    Properties = new Dictionary <string, string>();
                    Properties.Add("Before_Formula", cdwEditor.Before_Formula);
                    Properties.Add("After_Formula", cdwEditor.After_Formula);
                    json = cdwEditor.After_JSON;
                    cdwEditor.Close();
                    model = jsonConverter.Import(json);
                    Cml   = cmlConverter.Export(model);
                }
            }
            catch (Exception ex)
            {
                new ReportError(Telemetry, TopLeft, module, ex).ShowDialog();
            }

            return(result);
        }
Esempio n. 20
0
        private string CmlFromBytes(byte[] byteArray, long id)
        {
            string       cml = Encoding.UTF8.GetString(byteArray);
            CMLConverter cc  = new CMLConverter();

            Model.Model m      = cc.Import(cml);
            double      before = m.MeanBondLength;

            if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance ||
                before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
            {
                m.ScaleToAverageBondLength(Constants.StandardBondLength);
                double after = m.MeanBondLength;
                Debug.WriteLine($"Structure Id: {id} rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
            }

            return(cc.Export(m));
        }
Esempio n. 21
0
        private void EditLabels_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

#if !DEBUG
            try
#endif
            {
                if (!string.IsNullOrEmpty(_lastCml))
                {
                    using (EditorHost editorHost = new EditorHost(_lastCml, "LABELS"))
                    {
                        editorHost.ShowDialog(this);
                        if (editorHost.DialogResult == DialogResult.OK)
                        {
                            CMLConverter cc    = new CMLConverter();
                            var          clone = cc.Import(_lastCml);
                            Debug.WriteLine(
                                $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                            _undoStack.Push(clone);

                            Model m = cc.Import(editorHost.OutputValue);
                            m.Relabel(true);
                            _lastCml = cc.Export(m);

                            ShowChemistry($"Edited {m.ConciseFormula}", m);
                        }
                    }
                    TopMost = true;
                    TopMost = false;
                    Activate();
                }
            }
#if !DEBUG
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
#endif
        }
Esempio n. 22
0
        private void ImportStructure()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            using (new WaitCursor())
            {
                CMLConverter conv = new CMLConverter();

                var    expModel = (Model.Model)display1.Chemistry;
                double before   = expModel.MeanBondLength;
                expModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                double after = expModel.MeanBondLength;
                Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                expModel.Relabel();

                using (new WaitCursor())
                {
                    expModel.Molecules[0].ChemicalNames.Clear();
                    if (_allResults.IupacNames != null)
                    {
                        foreach (var di in _allResults.IupacNames)
                        {
                            var cn = new Model.ChemicalName();
                            cn.Name    = di.data;
                            cn.DictRef = "chebi:Iupac";
                            expModel.Molecules[0].ChemicalNames.Add(cn);
                        }
                    }
                    if (_allResults.Synonyms != null)
                    {
                        foreach (var di in _allResults.Synonyms)
                        {
                            var cn = new Model.ChemicalName();
                            cn.Name    = di.data;
                            cn.DictRef = "chebi:Synonym";
                            expModel.Molecules[0].ChemicalNames.Add(cn);
                        }
                    }
                    Cml = conv.Export(expModel);
                }
            }
        }
Esempio n. 23
0
        private void EditorHost_FormClosing(object sender, FormClosingEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (DialogResult != DialogResult.OK && e.CloseReason == CloseReason.UserClosing)
            {
                if (elementHost1.Child is Chem4Word.ACME.Editor editor &&
                    editor.IsDirty)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Do you wish to save your changes?");
                    sb.AppendLine("  Click 'Yes' to save your changes and exit.");
                    sb.AppendLine("  Click 'No' to discard your changes and exit.");
                    sb.AppendLine("  Click 'Cancel' to return to the form.");
                    DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                    switch (dr)
                    {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;

                    case DialogResult.Yes:
                        DialogResult = DialogResult.OK;
                        var model = editor.EditedModel;
                        model.RescaleForCml();
                        // Replace any temporary Ids which are Guids
                        model.ReLabelGuids();
                        CMLConverter cc = new CMLConverter();
                        OutputValue = cc.Export(model);
                        Telemetry.Write(module, "Verbose", $"Result: {DialogResult}");
                        Hide();
                        editor = null;
                        break;

                    case DialogResult.No:
                        Telemetry.Write(module, "Verbose", $"Result: {DialogResult}");
                        editor = null;
                        break;
                    }
                }
            }
        }
Esempio n. 24
0
        private void ImportStructure()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            using (new WaitCursor())
            {
                CMLConverter conv = new CMLConverter();

                var expModel = _lastModel;
                expModel.Relabel(true);

                using (new WaitCursor())
                {
                    expModel.Molecules.Values.First().Names.Clear();

                    if (_allResults.IupacNames != null)
                    {
                        foreach (var di in _allResults.IupacNames)
                        {
                            var cn = new TextualProperty();
                            cn.Value    = di.data;
                            cn.FullType = "chebi:Iupac";
                            expModel.Molecules.Values.First().Names.Add(cn);
                        }
                    }

                    if (_allResults.Synonyms != null)
                    {
                        foreach (var di in _allResults.Synonyms)
                        {
                            var cn = new TextualProperty();
                            cn.Value    = di.data;
                            cn.FullType = "chebi:Synonym";
                            expModel.Molecules.Values.First().Names.Add(cn);
                        }
                    }

                    Cml = conv.Export(expModel);
                }
            }
        }
Esempio n. 25
0
        public DialogResult Edit()
        {
            DialogResult result = DialogResult.Cancel;

            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Telemetry.Write(module, "Verbose", "Called");
                if (HasSettings)
                {
                    LoadSettings();
                }

                // Strip off Formulae and ChemicalNames as we don't edit them here
                CMLConverter cmlConverter = new CMLConverter();
                Model.Model  model        = cmlConverter.Import(Cml);
                foreach (Molecule molecule in model.Molecules)
                {
                    molecule.ChemicalNames.Clear();
                    molecule.Formulas.Clear();
                    molecule.ConciseFormula = "";
                }

                EditorHost host = new EditorHost(cmlConverter.Export(model));
                host.TopLeft = TopLeft;
                host.ShowDialog();
                result = host.Result;
                Cml    = host.OutputValue;
                host.Close();
                host.Dispose();
            }
            catch (Exception ex)
            {
                new ReportError(Telemetry, TopLeft, module, ex).ShowDialog();
            }

            return(result);
        }
Esempio n. 26
0
        private void btnConvertModel_Click(object sender, EventArgs e)
        {
            TextBoxFormat format = GetTextBoxFormat(txtStructure);

            switch (format)
            {
            case TextBoxFormat.Json:
                JSONConverter converter1 = new JSONConverter();
                Model         model1     = converter1.Import((object)txtStructure.Text);
                model1.RebuildMolecules();
                model1.Relabel();
                model1.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                CMLConverter converter2 = new CMLConverter();
                txtStructure.Text = converter2.Export(model1);
                break;

            case TextBoxFormat.Cml:
                CMLConverter converter3 = new CMLConverter();
                Model        model2     = converter3.Import((object)txtStructure.Text);
                model2.RebuildMolecules();
                model2.Relabel();
                JSONConverter converter4 = new JSONConverter();
                txtStructure.Text = converter4.Export(model2);
                break;

            case TextBoxFormat.MolFile:
                SdFileConverter converter5 = new SdFileConverter();
                Model           model3     = converter5.Import((object)txtStructure.Text);
                model3.RebuildMolecules();
                model3.Relabel();
                CMLConverter converter6 = new CMLConverter();
                txtStructure.Text = converter6.Export(model3);
                break;
            }

            EnableButtons();
        }
Esempio n. 27
0
        private void OnSaveClick(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered");

            try
            {
                if (CanSave())
                {
                    Cml = _cmlConvertor.Export(_model);

                    DialogResult = DialogResult.OK;
                }
                else
                {
                    UserInteractions.InformUser("Can't save because at least one user defined label contains an error");
                }
            }
            catch (Exception ex)
            {
                new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
            }
        }
Esempio n. 28
0
        public static void DoUpgrade(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            int sel = doc.Application.Selection.Range.Start;

            Globals.Chem4WordV3.DisableDocumentEvents(doc);

            try
            {
                string extension   = doc.FullName.Split('.').Last();
                string guid        = Guid.NewGuid().ToString("N");
                string timestamp   = DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
                string destination = Path.Combine(Globals.Chem4WordV3.AddInInfo.ProductAppDataPath, "Backups", $"Chem4Word-{timestamp}-{guid}.{extension}");
                File.Copy(doc.FullName, destination);
            }
            catch (Exception ex)
            {
                // Nothing much we can do here :-(
                Debug.WriteLine(ex.Message);
            }

            List <UpgradeTarget> targets = CollectData(doc);
            int upgradedCCs = 0;
            int upgradedXml = 0;

            foreach (var target in targets)
            {
                if (target.ContentControls.Count > 0)
                {
                    upgradedXml++;
                    upgradedCCs += target.ContentControls.Count;
                }
                foreach (var cci in target.ContentControls)
                {
                    foreach (Word.ContentControl cc in doc.ContentControls)
                    {
                        if (cc.ID.Equals(cci.Id))
                        {
                            if (cci.Type.Equals("2D"))
                            {
                                cc.LockContents = false;
                                cc.Title        = Constants.ContentControlTitle;
                                cc.Tag          = target.Model.CustomXmlPartGuid;
                                cc.LockContents = true;
                            }
                            else
                            {
                                cc.LockContents = false;
                                cc.Range.Delete();
                                int start = cc.Range.Start;
                                cc.Delete();
                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                bool   isFormula = false;
                                string source;
                                string text             = CustomRibbon.GetInlineText(target.Model, cci.Type, ref isFormula, out source);
                                Word.ContentControl ccn = CustomRibbon.Insert1D(doc.Application, doc, text, isFormula, $"{cci.Type}:{target.Model.CustomXmlPartGuid}");
                                ccn.LockContents = true;
                            }
                        }
                    }
                }

                CMLConverter  converter = new CMLConverter();
                CustomXMLPart cxml      = doc.CustomXMLParts.SelectByID(target.CxmlPartId);
                cxml.Delete();
                doc.CustomXMLParts.Add(converter.Export(target.Model));
            }

            EraseChemistryZones(doc);

            Globals.Chem4WordV3.EnableDocumentEvents(doc);
            doc.Application.Selection.SetRange(sel, sel);
            if (upgradedCCs + upgradedXml > 0)
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
                UserInteractions.AlertUser($"Upgrade Completed{Environment.NewLine}{Environment.NewLine}Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
            }
        }
        private void ExportFromLibrary_OnClick(object sender, RoutedEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered");

            try
            {
                string exportFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                VistaFolderBrowserDialog browser = new VistaFolderBrowserDialog();

                browser.Description            = "Select a folder to export your Library's structures as cml files";
                browser.UseDescriptionForTitle = true;
                browser.RootFolder             = Environment.SpecialFolder.Desktop;
                browser.ShowNewFolderButton    = false;
                browser.SelectedPath           = exportFolder;
                Forms.DialogResult dr = browser.ShowDialog();

                if (dr == Forms.DialogResult.OK)
                {
                    exportFolder = browser.SelectedPath;

                    if (Directory.Exists(exportFolder))
                    {
                        Forms.DialogResult doExport         = Forms.DialogResult.Yes;
                        string[]           existingCmlFiles = Directory.GetFiles(exportFolder, "*.cml");
                        if (existingCmlFiles.Length > 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine($"This folder contains {existingCmlFiles.Length} cml files.");
                            sb.AppendLine("Do you wish to continue?");
                            doExport = UserInteractions.AskUserYesNo(sb.ToString(), Forms.MessageBoxDefaultButton.Button2);
                        }
                        if (doExport == Forms.DialogResult.Yes)
                        {
                            Database.Library lib = new Database.Library();

                            int exported = 0;
                            int progress = 0;

                            List <ChemistryDTO> dto = lib.GetAllChemistry(null);
                            int total = dto.Count;
                            if (total > 0)
                            {
                                ProgressBar.Maximum          = dto.Count;
                                ProgressBar.Minimum          = 0;
                                ProgressBarHolder.Visibility = Visibility.Visible;
                                SetButtonState(false);

                                var converter = new CMLConverter();

                                foreach (var obj in dto)
                                {
                                    progress++;
                                    ShowProgress(progress, $"Structure #{obj.Id} [{progress}/{total}]");

                                    var filename = Path.Combine(browser.SelectedPath, $"Chem4Word-{obj.Id:000000000}.cml");

                                    Model model = converter.Import(obj.Cml);

                                    var outcome = model.EnsureBondLength(Globals.Chem4WordV3.SystemOptions.BondLength, false);
                                    if (!string.IsNullOrEmpty(outcome))
                                    {
                                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", outcome);
                                    }

                                    File.WriteAllText(filename, converter.Export(model));
                                    exported++;
                                }
                            }

                            ProgressBarHolder.Visibility = Visibility.Collapsed;
                            SetButtonState(true);

                            if (exported > 0)
                            {
                                UserInteractions.InformUser($"Exported {exported} structures to {browser.SelectedPath}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ProgressBarHolder.Visibility = Visibility.Collapsed;
                SetButtonState(true);

                new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
Esempio n. 30
0
        public static void DoUpgrade(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            int sel = doc.Application.Selection.Range.Start;

            Globals.Chem4WordV3.DisableDocumentEvents(doc);

            try
            {
                string extension   = doc.FullName.Split('.').Last();
                string guid        = Guid.NewGuid().ToString("N");
                string timestamp   = DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
                string destination = Path.Combine(Globals.Chem4WordV3.AddInInfo.ProductAppDataPath, "Backups", $"Chem4Word-{timestamp}-{guid}.{extension}");
                File.Copy(doc.FullName, destination);
            }
            catch (Exception ex)
            {
                // Nothing much we can do here :-(
                Debug.WriteLine(ex.Message);
            }

            Dictionary <string, CustomXMLPart> customXmlParts = new Dictionary <string, CustomXMLPart>();
            List <UpgradeTarget> targets = CollectData(doc);
            int upgradedCCs = 0;
            int upgradedXml = 0;

            foreach (var target in targets)
            {
                if (target.ContentControls.Count > 0)
                {
                    upgradedXml++;
                    upgradedCCs += target.ContentControls.Count;
                }

                foreach (var cci in target.ContentControls)
                {
                    foreach (Word.ContentControl cc in doc.ContentControls)
                    {
                        if (cc.ID.Equals(cci.Id))
                        {
                            int    start;
                            bool   isFormula;
                            string source;
                            string text;

                            switch (cci.Type)
                            {
                            case "2D":
                                cc.LockContents = false;
                                cc.Title        = Constants.ContentControlTitle;
                                cc.Tag          = target.Model.CustomXmlPartGuid;
                                cc.LockContents = true;

                                // ToDo: Regenerate converted 2D structures
                                break;

                            case "new":
                                cc.LockContents = false;
                                cc.Range.Delete();
                                start = cc.Range.Start;
                                cc.Delete();

                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                var model    = new Model.Model();
                                var molecule = new Molecule();
                                molecule.ChemicalNames.Add(new ChemicalName {
                                    Id = "m1.n1", Name = cci.Text, DictRef = Constants.Chem4WordUserSynonym
                                });
                                model.Molecules.Add(molecule);
                                model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");

                                var cmlConvertor = new CMLConverter();
                                doc.CustomXMLParts.Add(cmlConvertor.Export(model));

                                Word.ContentControl ccn = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);
                                ChemistryHelper.Insert1D(ccn, cci.Text, false, $"m1.n1:{model.CustomXmlPartGuid}");
                                ccn.LockContents = true;
                                break;

                            default:
                                cc.LockContents = false;
                                cc.Range.Delete();
                                start = cc.Range.Start;
                                cc.Delete();

                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                isFormula = false;
                                text      = ChemistryHelper.GetInlineText(target.Model, cci.Type, ref isFormula, out source);
                                Word.ContentControl ccr = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);
                                ChemistryHelper.Insert1D(ccr, text, isFormula, $"{cci.Type}:{target.Model.CustomXmlPartGuid}");
                                ccr.LockContents = true;
                                break;
                            }
                        }
                    }
                }

                CMLConverter  converter = new CMLConverter();
                CustomXMLPart cxml      = doc.CustomXMLParts.SelectByID(target.CxmlPartId);
                if (customXmlParts.ContainsKey(cxml.Id))
                {
                    customXmlParts.Add(cxml.Id, cxml);
                }
                doc.CustomXMLParts.Add(converter.Export(target.Model));
            }

            EraseChemistryZones(doc);

            foreach (var kvp in customXmlParts.ToList())
            {
                kvp.Value.Delete();
            }

            Globals.Chem4WordV3.EnableDocumentEvents(doc);
            doc.Application.Selection.SetRange(sel, sel);
            if (upgradedCCs + upgradedXml > 0)
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
                UserInteractions.AlertUser($"Upgrade Completed{Environment.NewLine}{Environment.NewLine}Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
            }
        }