Esempio n. 1
0
        /// <summary>
        /// Create an OpenXml Word Document from the CML
        /// </summary>
        /// <param name="cml">Input Chemistry</param>
        /// <param name="guid">Bookmark to create</param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static string CreateFromCml(string cml, string guid, Options options, IChem4WordTelemetry telemetry, Point topLeft)
        {
            CMLConverter cc = new CMLConverter();

            Model.Model m = cc.Import(cml);

            string fileName = Path.Combine(Path.GetTempPath(), $"Chem4Word-V3-{guid}.docx");

            bool canRender = m.AllAtoms.Count > 0 && (m.MeanBondLength > Constants.BondLengthTolerance / 2 || m.AllBonds.Count == 0);

            if (canRender)
            {
                string bookmarkName = "C4W_" + guid;

                // Create a Wordprocessing document.
                using (WordprocessingDocument package = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
                {
                    // Add a new main document part.
                    MainDocumentPart mdp = package.AddMainDocumentPart();
                    mdp.Document = new Document(new Body());
                    Body docbody = package.MainDocumentPart.Document.Body;

                    // This is for test
                    //AddParagraph(docbody, "Hello World", bookmarkName);
                    // This will be live
                    AddPictureFromModel(docbody, m, bookmarkName, options, telemetry, topLeft);

                    // Save changes to the main document part.
                    package.MainDocumentPart.Document.Save();
                }
            }

            return(fileName);
        }
Esempio n. 2
0
        private void HandleDataContextChanged()
        {
            ChemistryModel chemistryModel = null;

            if (Chemistry is string)
            {
                var data = Chemistry as string;
                if (!string.IsNullOrEmpty(data))
                {
                    if (data.StartsWith("<"))
                    {
                        var conv = new CMLConverter();
                        chemistryModel = conv.Import(data);
                    }
                    if (data.Contains("M  END"))
                    {
                        var conv = new SdFileConverter();
                        chemistryModel = conv.Import(data);
                    }
                }
            }
            else
            {
                if (Chemistry != null && !(Chemistry is ChemistryModel))
                {
                    throw new ArgumentException("Object must be of type 'Chem4Word.Model.Model'.");
                }
                chemistryModel = Chemistry as ChemistryModel;
            }

            if (chemistryModel != null)
            {
                if (chemistryModel.AllAtoms.Count > 0)
                {
                    chemistryModel.RescaleForXaml(Constants.StandardBondLength * 2);

                    Debug.WriteLine($"Ring count == {chemistryModel.Molecules.SelectMany(m => m.Rings).Count()}");

                    if (ShowCarbonLabels)
                    {
                        foreach (var atom in chemistryModel.AllAtoms)
                        {
                            if (atom.Element.Equals(Globals.PeriodicTable.C))
                            {
                                atom.ShowSymbol = true;
                            }
                        }
                    }
                    Placeholder.DataContext = chemistryModel;
                }
                else
                {
                    Placeholder.DataContext = null;
                }
            }
            else
            {
                Placeholder.DataContext = null;
            }
        }
Esempio n. 3
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. 4
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. 5
0
        public static void RefreshAllStructures(Word.Document doc)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            IChem4WordRenderer renderer =
                Globals.Chem4WordV3.GetRendererPlugIn(
                    Globals.Chem4WordV3.SystemOptions.SelectedRendererPlugIn);

            if (renderer != null)
            {
                foreach (CustomXMLPart xmlPart in doc.CustomXMLParts)
                {
                    var cml = xmlPart.XML;

                    var          cxmlId = CustomXmlPartHelper.GetCmlId(xmlPart);
                    CMLConverter cc     = new CMLConverter();
                    var          model  = cc.Import(cml);

                    renderer.Properties = new Dictionary <string, string>();
                    renderer.Properties.Add("Guid", cxmlId);
                    renderer.Cml = cml;

                    string tempfileName = renderer.Render();
                    if (File.Exists(tempfileName))
                    {
                        UpdateThisStructure(doc, model, cxmlId, tempfileName);
                    }
                }
            }
        }
Esempio n. 6
0
        public void CmlImportNested()
        {
            CMLConverter mc    = new CMLConverter();
            Model        model = mc.Import(ResourceHelper.GetStringResource("NestedMolecules.xml"));

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

            Assert.True(molecule.Molecules.Count == 4, $"Expected 4 Molecule; Got {molecule.Molecules.Count}");
            Assert.True(molecule.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule.Atoms.Count}");
            // Check molecule m2 has no child molecules and 6 atoms
            molecule = model.Molecules.Values.First().Molecules.Values.ToList()[1];
            Assert.True(molecule.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule.Molecules.Count}");
            Assert.True(molecule.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule.Atoms.Count}");
            // Check molecule m1 has 1 child molecules and no atoms
            molecule = model.Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule.Molecules.Count == 1, $"Expected 1 Molecule; Got {molecule.Molecules.Count}");
            Assert.True(molecule.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule.Atoms.Count}");
            // Check molecule m5 has 1 child molecules and 6 atoms
            molecule = model.Molecules.Values.First().Molecules.Values.First().Molecules.Values.First();
            Assert.True(molecule.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule.Molecules.Count}");
            Assert.True(molecule.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule.Atoms.Count}");
        }
Esempio n. 7
0
        private void EditorHost_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Cursor.Current = Cursors.WaitCursor;

            if (TopLeft.X != 0 && TopLeft.Y != 0)
            {
                Left = (int)TopLeft.X;
                Top  = (int)TopLeft.Y;
            }

            CMLConverter  cc = new CMLConverter();
            JSONConverter jc = new JSONConverter();

            Model.Model model = cc.Import(_cml);

            WpfChemDoodle editor = new WpfChemDoodle();

            editor.Telemetry          = Telemetry;
            editor.ProductAppDataPath = ProductAppDataPath;
            editor.UserOptions        = UserOptions;
            editor.TopLeft            = TopLeft;

            editor.StructureJson     = jc.Export(model);
            editor.IsSingleMolecule  = model.Molecules.Count == 1;
            editor.AverageBondLength = model.MeanBondLength;

            editor.InitializeComponent();
            elementHost1.Child    = editor;
            editor.OnButtonClick += OnWpfButtonClick;

            this.Show();
            Application.DoEvents();
        }
Esempio n. 8
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. 9
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. 10
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. 11
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. 12
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. 13
0
        /// <summary>
        /// Occurs after a new custom XMl part is loaded into the document
        /// Useful for updating the Navigator
        /// </summary>
        /// <param name="NewPart"></param>
        private void OnPartAfterLoad(CustomXMLPart NewPart)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                var converter = new CMLConverter();
                //get the chemistry
                var chemModel = converter.Import(NewPart.XML);
                //find out which content control macthes the custom XML part
                try
                {
                    // ReSharper disable once InconsistentNaming
                    var matchingCC = (from ContentControl cc in _doc.ContentControls
                                      orderby cc.Range.Start
                                      where CustomXmlPartHelper.GuidFromTag(cc?.Tag) == CustomXmlPartHelper.GetCmlId(NewPart)
                                      select cc).First();

                    //get the ordinal position of the content control
                    int start = 0;
                    foreach (ContentControl cc in _doc.ContentControls)
                    {
                        if (cc.ID == matchingCC.ID)
                        {
                            break;
                        }
                        start += 1;
                    }

                    //insert the new navigator item at the ordinal position
                    var newNavItem = new NavigatorItem()
                    {
                        CMLId             = matchingCC?.Tag,
                        ChemicalStructure = NewPart.XML,
                        XMLPart           = NewPart,
                        Name = chemModel.ConciseFormula
                    };
                    try
                    {
                        NavigatorItems.Insert(start, newNavItem);
                    }
                    catch (ArgumentOutOfRangeException) //can happen when there are more content controls than navigator items
                    {
                        //so simply insert the new navigator item at the end
                        NavigatorItems.Add(newNavItem);
                    }
                }
                catch (InvalidOperationException)
                {
                    //sequence contains no elements - thrown on close
                    //just ignore
                }
            }
            catch (Exception ex)
            {
                new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
            }
        }
Esempio n. 14
0
        private void ClearChemistry_Click(object sender, EventArgs e)
        {
            var cc = new CMLConverter();

            _undoStack.Push(cc.Import(_lastCml));
            _lastCml = "<cml></cml>";

            Display.Clear();
            EnableUndoRedoButtons();
        }
Esempio n. 15
0
        public void SetProperties(string cml, List <string> used1DProperties, AcmeOptions options)
        {
            CMLConverter cc = new CMLConverter();

            _model = cc.Import(cml, used1DProperties);

            _used1DProperties = used1DProperties;
            EditorOptions     = options;

            InitialiseEditor();
        }
Esempio n. 16
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. 17
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. 18
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. 19
0
        public void CmlImportNoAtoms()
        {
            CMLConverter mc = new CMLConverter();
            Model        m  = mc.Import(ResourceHelper.GetStringResource("NoAtoms.xml"));

            // Basic sanity checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 0, $"Expected 0 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 0, $"Expected 0 Bonds; Got {m.TotalBondsCount}");

            // Check that names and formulae have not been trashed
            Assert.True(m.Molecules.Values.First().Names.Count == 1, $"Expected 1 Chemical Names; Got {m.Molecules.Values.First().Names.Count}");
        }
Esempio n. 20
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. 21
0
        private void HandleDataContextChanged()
        {
            Model chemistryModel = null;

            if (Chemistry is string)
            {
                var data = Chemistry as string;
                if (!string.IsNullOrEmpty(data))
                {
                    if (data.StartsWith("<"))
                    {
                        var conv = new CMLConverter();
                        chemistryModel = conv.Import(data);
                        chemistryModel.EnsureBondLength(20, false);
                    }
                    if (data.Contains("M  END"))
                    {
                        var conv = new SdFileConverter();
                        chemistryModel = conv.Import(data);
                        chemistryModel.EnsureBondLength(20, false);
                    }
                }
            }
            else
            {
                if (Chemistry != null && !(Chemistry is Model))
                {
                    Debugger.Break();
                    throw new ArgumentException($"Object must be of type {nameof(Model)}.");
                }
                chemistryModel = Chemistry as Model;
                if (chemistryModel != null)
                {
                    chemistryModel.EnsureBondLength(20, false);
                }
            }

            //assuming we've got this far, we should have something we can draw
            if (chemistryModel != null)
            {
                if (chemistryModel.TotalAtomsCount > 0)
                {
                    chemistryModel.RescaleForXaml(true, Constants.StandardBondLength);

                    CurrentViewModel = new ViewModel(chemistryModel);
                    CurrentViewModel.SetTextParams(chemistryModel.XamlBondLength);
                    DrawChemistry(CurrentViewModel);
                }
            }
        }
Esempio n. 22
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. 23
0
        /// <summary>
        /// Create an OpenXml Word Document from the CML
        /// </summary>
        /// <param name="cml">Input Chemistry</param>
        /// <param name="guid">Bookmark to create</param>
        /// <param name="options"></param>
        /// <param name="telemetry"></param>
        /// <param name="topLeft"></param>
        /// <returns></returns>
        public static string CreateFromCml(string cml, string guid, OoXmlV4Options options, IChem4WordTelemetry telemetry, Point topLeft)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            CMLConverter cc    = new CMLConverter();
            Model        model = cc.Import(cml);

            if (model.AllErrors.Count > 0 || model.AllWarnings.Count > 0)
            {
                if (model.AllErrors.Count > 0)
                {
                    telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllErrors));
                }

                if (model.AllWarnings.Count > 0)
                {
                    telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllWarnings));
                }
            }

            string fileName = string.Empty;

            bool canRender = model.TotalAtomsCount > 0 &&
                             (model.TotalBondsCount == 0 ||
                              model.MeanBondLength > Core.Helpers.Constants.BondLengthTolerance / 2);

            if (canRender)
            {
                fileName = Path.Combine(Path.GetTempPath(), $"Chem4Word-V3-{guid}.docx");

                string bookmarkName = Core.Helpers.Constants.OoXmlBookmarkPrefix + guid;

                // Create a Wordprocessing document.
                using (WordprocessingDocument package = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document))
                {
                    // Add a new main document part.
                    MainDocumentPart mdp = package.AddMainDocumentPart();
                    mdp.Document = new Document(new Body());
                    Body docbody = package.MainDocumentPart.Document.Body;

                    // This will be live
                    AddPictureFromModel(docbody, model, bookmarkName, options, telemetry, topLeft);

                    // Save changes to the main document part.
                    package.MainDocumentPart.Document.Save();
                }
            }

            return(fileName);
        }
Esempio n. 24
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. 25
0
        /// <summary>
        /// Loads up the model initially from the document
        /// </summary>
        private void LoadModel()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                var converter = new CMLConverter();
                if (NavigatorItems.Any())
                {
                    NavigatorItems.Clear();
                }
                if (_doc != null)
                {
                    Dictionary <string, int> added = new Dictionary <string, int>();

                    var navItems = from ContentControl ccs in _doc.ContentControls
                                   join CustomXMLPart part in _parts
                                   on CustomXmlPartHelper.GuidFromTag(ccs?.Tag) equals CustomXmlPartHelper.GetCmlId(part)
                                   orderby ccs.Range.Start
                                   let chemModel = converter.Import(part.XML)
                                                   select new NavigatorItem
                    {
                        CMLId = ccs?.Tag, ChemicalStructure = part.XML, XMLPart = part, Name = chemModel.ConciseFormula
                    };

                    foreach (NavigatorItem navigatorItem in navItems)
                    {
                        string guid = CustomXmlPartHelper.GuidFromTag(navigatorItem.CMLId);
                        if (!string.IsNullOrEmpty(guid))
                        {
                            if (!added.ContainsKey(guid))
                            {
                                NavigatorItems.Add(navigatorItem);
                                added.Add(guid, 1);
                            }
                        }
                    }

                    Debug.WriteLine("Number of items loaded = {0}", NavigatorItems.Count);
                }
            }
            catch (Exception ex)
            {
                using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex))
                {
                    form.ShowDialog();
                }
            }
        }
Esempio n. 26
0
        public override void Execute(object parameter)
        {
            CMLConverter    cmlConverter = new CMLConverter();
            SdFileConverter sdfConverter = new SdFileConverter();

            if (Clipboard.ContainsData(Globals.FormatCML))
            {
                string pastedCML = (string)Clipboard.GetData(Globals.FormatCML);
                EditViewModel.PasteCML(pastedCML);
            }
            else if (Clipboard.ContainsText())
            {
                bool   failedCML  = false;
                bool   failedSDF  = false;
                string pastedText = Clipboard.GetText();
                Model  buffer     = null;
                //try to convert the pasted text with the CML converter first
                try
                {
                    buffer = cmlConverter.Import(pastedText);
                }
                catch
                {
                    failedCML = true;
                }

                if (failedCML)
                {
                    buffer    = sdfConverter.Import(pastedText);
                    failedSDF = buffer.GeneralErrors.Any();
                }

                if (failedCML & failedSDF)
                {
                    if (buffer.GeneralErrors.Any())
                    {
                        Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: " + buffer.GeneralErrors[0]);
                    }
                    else
                    {
                        Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: unknown error.");
                    }
                }
                else
                {
                    EditViewModel.PasteModel(buffer);
                }
            }
        }
Esempio n. 27
0
        public void CmlImportCopperPhthalocyanine()
        {
            CMLConverter mc = new CMLConverter();
            Model        m  = mc.Import(ResourceHelper.GetStringResource("CopperPhthalocyanine.xml"));

            // Basic Sanity Checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 57, $"Expected 57 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 68, $"Expected 68 Bonds; Got {m.TotalBondsCount}");

            Assert.True(m.Molecules.Values.First().Rings.Count == 12, $"Expected 12 Rings; Got {m.Molecules.Values.First().Rings.Count}");
            var list = m.Molecules.Values.First().SortRingsForDBPlacement();

            Assert.True(list.Count == 12, $"Expected 12 Rings; Got {list.Count}");
        }
Esempio n. 28
0
        public void CmlImportPhthalocyanineThenRefresh()
        {
            CMLConverter mc = new CMLConverter();
            Model        m  = mc.Import(ResourceHelper.GetStringResource("Phthalocyanine.xml"));

            // Basic Sanity Checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 58, $"Expected 58 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 66, $"Expected 66 Bonds; Got {m.TotalBondsCount}");

            Assert.True(m.Molecules.Values.First().Rings.Count == 9, $"Expected 9 Rings; Got {m.Molecules.Values.First().Rings.Count}");
            var list = m.Molecules.Values.First().SortRingsForDBPlacement();

            Assert.True(list.Count == 8, $"Expected 8 Rings; Got {list.Count}");
        }
Esempio n. 29
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. 30
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);
        }