Example #1
0
        /// <summary>
        /// Get additional data from the broker
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>

        public override object GetAdditionalData(
            string command)
        {
            if (!SmallWorldDao.SmallWorldDepictionsAvailable)
            {
                return(null);
            }

            if (SwDao != null && SwDao.Swp != null)
            {
                string cmdName, mcName, colorArg, alignArg;
                bool   color, align;
                SmallWorldPredefinedParameters swp = SwDao.Swp;

                Lex.Split(command, " ", out cmdName, out mcName, out colorArg, out alignArg);

                if (Lex.Ne(cmdName, "GetDepictions") ||
                    !bool.TryParse(colorArg, out color) ||
                    !bool.TryParse(alignArg, out align))
                {
                    return(null);
                }

                string dls = SwDao.GetDepictionsAsMultiRecordText(color, align);
                return(dls);
            }

            else
            {
                throw new Exception("GetAdditionalData failed for: " + command);
            }
        }
Example #2
0
        /// <summary>
        /// Update depiction style
        /// </summary>
        /// <param name="psc"></param>

        public void UpdateDepictions(ParsedStructureCriteria psc)
        {
            SmallWorldPredefinedParameters swp = psc.SmallWorldParameters;             // new values

            if (Qm == null || Qm.ResultsFormatter == null ||
                Qm.ResultsFormatter.StructureHighlightPssc == null ||
                Qm.ResultsFormatter.StructureHighlightPssc.SmallWorldParameters == null)
            {
                return;
            }

            ResultsFormatter fmtr = Qm.ResultsFormatter;
            SmallWorldPredefinedParameters swp2 =             // current view values
                                                  fmtr.StructureHighlightPssc.SmallWorldParameters;

            psc.Highlight = swp2.Highlight = swp.Highlight;
            psc.Align     = swp2.Align = swp.Align;

            int i = SmallWorldData.GetSvgOptionsIndex(swp2.Highlight, swp2.Align);
            SmallWorldDepictions d = fmtr.SmallWorldDepictions;

            if ((swp.Highlight || swp.Align) && d != null && i != 0 && d.SvgDict[i] == null)           // need to start retrieval for depiction type we don't alread have?
            {
                d.StartDepictionRetrieval(Qm, psc.QueryColumn, swp2.Highlight, swp2.Align);
                return;                 // leave display as is for now
            }

            else                                                           // clear current decpiction so new one shows
            {
                Qm.DataTableManager.ResetFormattedValues(psc.QueryColumn); // clear existing bitmaps
                Qm.MoleculeGrid.RefreshDataSource();
            }

            return;
        }
Example #3
0
        /// <summary>
        /// Convert parameter string to SmallWorldParameters object
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>

        static SmallWorldPredefinedParameters ToSwp(string s)
        {
            SmallWorldPredefinedParameters swp = null;
            bool ok = SmallWorldPredefinedParameters.TryParse(s, out swp);

            return(swp);
        }
Example #4
0
        bool UpdateAssociatedSmallWorldQueryColumns(
            ParsedStructureCriteria psc)
        {
            if (Qc == null || Qc.QueryTable == null)
            {
                return(false);
            }

            SmallWorldPredefinedParameters swp = psc.SmallWorldParameters;

            if (swp == null)
            {
                return(false);
            }

            MetaTable mt = Qc.MetaColumn.MetaTable;

            if (Lex.Eq(mt.Name, MetaTable.SmallWorldMetaTableName))             // special SmallWorld table
            {
                string dbCriteria = Lex.IsDefined(swp.Database) ? "Database in (" + swp.Database + ")" : "";
                SetSwQcCriteria("Database", dbCriteria, swp.Database);

                SetSwQcCriteria("distance", swp.Distance.Format());
                SetSwQcCriteria("terminalUp", swp.TerminalUp.Format());
                SetSwQcCriteria("terminalDown", swp.TerminalDown.Format());
                SetSwQcCriteria("ringUp", swp.RingUp.Format());
                SetSwQcCriteria("ringDown", swp.RingDown.Format());
                SetSwQcCriteria("linkerUp", swp.LinkerUp.Format());
                SetSwQcCriteria("linkerDown", swp.LinkerDown.Format());
                SetSwQcCriteria("minorMutations", swp.MutationMinor.Format());
                SetSwQcCriteria("majorMutations", swp.MutationMajor.Format());
                SetSwQcCriteria("substitutions", swp.SubstitutionRange.Format());
                SetSwQcCriteria("hybridisation", swp.HybridisationChange.Format());

                return(true);
            }

            else if (mt.DatabaseListMetaColumn != null)             // basic structure table
            {
                MetaColumn  dbSetMc = mt.DatabaseListMetaColumn;
                QueryColumn dbSetQc = Qc.QueryTable.GetQueryColumnByName(dbSetMc.Name);
                if (dbSetQc == null)
                {
                    return(false);
                }

                dbSetQc.Criteria        = dbSetMc.Name + " in (" + swp.Database + ")";
                dbSetQc.CriteriaDisplay = swp.Database;
                return(true);
            }

            else
            {
                return(false);             // no other cols
            }
        }
Example #5
0
        private void ShowColors_CheckedChanged(object sender, EventArgs e)
        {
            if (InSetup)
            {
                return;
            }

            SmallWorldPredefinedParameters swp = null;

            if (!GetValues(out swp))
            {
                return;
            }
            Swp = swp;
            UpdateDepictions();
        }
Example #6
0
/// <summary>
/// Try to get option values checking for errors
/// </summary>
/// <returns></returns>

        bool GetValues(
            out SmallWorldPredefinedParameters swp)
        {
            int maxHits = 0;

            swp = new SmallWorldPredefinedParameters();

            if (Lex.IsUndefined(DatabaseComboBox.Text))
            {
                MessageBoxMx.ShowError("Database to search must be defined");
                return(false);
            }
            swp.Database = DatabaseComboBox.Text;             // one or more database names

            swp.Distance = new RangeParm(DistanceRange.Value.Minimum, DistanceRange.Value.Maximum);

            if (!TryParseMaxHits(out maxHits))
            {
                return(false);
            }
            swp.MaxHits = maxHits;

            swp.TerminalUp   = TerminalRangeUp.GetRange();
            swp.TerminalDown = TerminalRangeDown.GetRange();

            swp.RingUp   = RingRangeUp.GetRange();
            swp.RingDown = RingRangeDown.GetRange();

            swp.LinkerUp   = LinkerRangeUp.GetRange();
            swp.LinkerDown = LinkerRangeDown.GetRange();

            swp.MatchAtomTypes = MatchAtomTypes.Checked;

            swp.MutationMinor = MutationRangeMinor.GetRange();
            swp.MutationMajor = MutationRangeMajor.GetRange();

            swp.SubstitutionRange   = SubstitutionRange.GetRange();
            swp.HybridisationChange = HybridizationRange.GetRange();

            swp.PresetName = PresetsComboBox.Text;

            swp.Highlight = ShowColors.Checked;
            swp.Align     = AlignStructs.Checked;

            return(true);
        }
Example #7
0
        private void AtomTypeMatch_CheckedChanged(object sender, EventArgs e)
        {
            if (InSetup)
            {
                return;
            }

            SmallWorldPredefinedParameters swp = null;

            if (!GetValues(out swp))
            {
                return;
            }
            Swp = swp;
            Setup(Swp);             // adjust other form elements

            EditValueChanged();
        }
Example #8
0
        /// <summary>
        /// Execute SmallWorld search
        /// </summary>
        /// <param name="eqp"></param>

        void ExecuteSmallWorldSearch(
            ExecuteQueryParms eqp)
        {
            if (!SmallWorldDao.IsSmallWorldAvailable())
            {
                throw new UserQueryException("SmallWorld searching is not currently available.");
            }

            Query      q  = eqp.QueryTable.Query;
            QueryTable qt = eqp.QueryTable;

            SmallWorldPredefinedParameters swp = Pssc.SmallWorldParameters;
            string smiles = Pssc.Molecule.GetSmilesString();

            swp.Smiles = smiles;
            //swp.Database = "Corp";

            LastSwNonSqlBroker = null;     // debug - force new broker

            if (SwDao == null)             // if Dao not allocated then allocate & execute the search
            {
                if (LastSwNonSqlBroker != null && LastSwNonSqlBroker.Pssc != null && LastSwNonSqlBroker.Pssc.SmallWorldParameters != null &&
                    LastSwNonSqlBroker.Pssc.SmallWorldParameters.Serialize() == swp.Serialize())
                {
                    SwDao = LastSwNonSqlBroker.SwDao;                     // get rows from previous search
                    SwDao.BuildSwToQeColumnMap(SelectList);               // reset the column map for this broker instance
                }

                else
                {
                    SwDao = new SmallWorldDao();
                    SwDao.KeysToExclude = q.KeysToExclude;
                    SwDao.ExecuteSearch(swp);
                    SwDao.BuildSwToQeColumnMap(SelectList);        //
                    LastSwNonSqlBroker = this;                     // remember for future use
                }
            }

            BuildSmallWorldQueryEngineRows(eqp);             // build the QE row set (filtered) from the SW rowset

            return;
        }
Example #9
0
        SmallWorldPredefinedParameters GetDefaultSmallWorldOptions()
        {
            SmallWorldPredefinedParameters swp = SmallWorld;

            string prefs = Preferences.Get("DefaultSmallWorldOptions");

            if (Lex.IsUndefined(prefs))
            {
                return(CustomSettings);
            }

            if (!SmallWorldPredefinedParameters.TryParse(prefs, out swp))
            {
                return(CustomSettings);
            }

            CustomSettings = swp;
            OptionPresets[CustomSettings.PresetName] = swp;             // store in dict
            return(swp);
        }
Example #10
0
        private void SavePreferredSettings()
        {
            SmallWorldPredefinedParameters swp = new SmallWorldPredefinedParameters();

            if (!GetValues(out swp))
            {
                return;
            }

            swp.PresetName = CustomSettings.PresetName;
            string prefs = swp.Serialize();

            Preferences.Set("DefaultSmallWorldOptions", prefs);

            OptionPresets[CustomSettings.PresetName] = swp;
            CustomSettings = swp;

            if (FindStandardPresetMatchingCustomSettings() == null)
            {
                PresetsComboBox.Text = "Custom";
            }
        }
Example #11
0
        /// <summary>
        /// User picked new preset
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void PresetsComboBox_EditValueChanged(object sender, EventArgs e)
        {
            if (InSetup)
            {
                return;
            }

            string txt = PresetsComboBox.Text;

            if (!OptionPresets.ContainsKey(txt))
            {
                return;                                              // shouldn't happen
            }
            SmallWorldPredefinedParameters opts = OptionPresets[txt];

            if (opts == null)
            {
                return;                           // shouldn't happen
            }
            Setup(opts);
            Refresh();
            EditValueChanged();
        }
Example #12
0
        /// <summary>
        /// Display proper options subform or hide options if not showing
        /// based on the Psc settings
        /// </summary>

        void SetupOptions(bool initialSetup = false)
        {
            FormMetricsInfo fmi = WindowsHelper.GetFormMetrics(this);

            SetupDepth++;
            bool showOptions = ShowOptions;

            if (Psc.SearchType != StructureSearchType.Unknown)
            // && Psc.SearchType != StructureSearchType.SSS) // don't show SS options for now
            {
                ShowOptionsButton.Enabled = true;
            }

            else             // no options available
            {
                showOptions = false;
                ShowOptionsButton.Enabled = false;
            }

            ShowOptionsButton.ImageIndex = (showOptions ? 1 : 0);                                             // set proper ShowOptions Expand/Contract image button
            BottomDivider.Visible        = (showOptions || Psc.SearchType == StructureSearchType.SmallWorld); // line above OK/Cancel

            if (Psc.SearchType == StructureSearchType.Substructure)
            {
                FSOptions.Visible = SimOptions.Visible = SmallWorldOptions.Visible = PreviewPanel.Visible = false;
                SSOptions.Visible = showOptions;

                int optHeight = showOptions ? SSOptions.Height + BottomCtlsHeight : 0;
                Size = new Size(InitialFormSize.Width, InitialFormSize.Height + optHeight);
                SSOptions.Setup(Psc);
            }

            else if (Psc.SearchType == StructureSearchType.MolSim)
            {
                SSOptions.Visible  = FSOptions.Visible = SmallWorldOptions.Visible = PreviewPanel.Visible = false;
                SimOptions.Visible = showOptions;
                int optHeight = showOptions ? SimOptions.Height + BottomCtlsHeight : 0;
                Size = new Size(InitialFormSize.Width, InitialFormSize.Height + optHeight);
                SimOptions.Setup(Psc);
            }

            else if (Psc.SearchType == StructureSearchType.FullStructure)
            {
                SSOptions.Visible = SimOptions.Visible = SmallWorldOptions.Visible = PreviewPanel.Visible = false;
                FSOptions.Visible = showOptions;

                int optHeight = showOptions ? FSOptions.Height + BottomCtlsHeight : 0;
                Size = new Size(InitialFormSize.Width, InitialFormSize.Height + optHeight);
                FSOptions.Setup(Psc);
            }

            else if (Psc.SearchType == StructureSearchType.SmallWorld)
            {
                SSOptions.Visible         = FSOptions.Visible = SimOptions.Visible = false;
                SmallWorldOptions.Visible = showOptions;

                SmallWorldOptions.CriteriaStructureForm = this;                 // link SmallWorldOptions to us

                SmallWorldPredefinedParameters swp = Psc.SmallWorldParameters;

                SmallWorldOptions.Setup(swp);

                Size = SmallWorldSize;                 // set form size same as last time

                if (!PreviewPanel.Visible)             // if preview not visible then adjust size and show
                {
                    PreviewCtl.InitializeView();

                    Size cs = this.ClientRectangle.Size;
                    PreviewPanel.Width   = cs.Width - PreviewPanel.Left - 2;
                    PreviewPanel.Height  = BottomDivider.Top - PreviewPanel.Top + 2;
                    PreviewPanel.Visible = true;
                }

                if (initialSetup)
                {
                    SmallWorldOptions.StartInitialQueryExecution();                               // start search if initial setup
                }
            }

            else
            {
                Size = InitialFormSize;              // no search type
            }
            Refresh();

            SetupDepth--;
            return;
        }
Example #13
0
        /// <summary>
        /// Initialize for any structure hilighting
        /// </summary>

        void InitializeStructureHilighting()
        {
            QueryColumn qc = null;

            if (StructureHighlightingInitialized)
            {
                return;
            }

            // Structure match hilighting / orienting

            try
            {
                do
                {
                    qc = Query.GetFirstStructureCriteriaColumn();
                    if (qc == null)
                    {
                        break;
                    }
                    if (Lex.IsUndefined(qc.Criteria))
                    {
                        break;
                    }

                    ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc);
                    if (psc == null || Lex.IsUndefined(psc.Value))
                    {
                        break;
                    }

                    ParsedStructureCriteria pssc = ParsedStructureCriteria.ConvertFromPscToPssc(psc);

                    StructureDisplayFormat sdf = StructureDisplayFormat.Deserialize(qc.DisplayFormatString);                     // get any hilighting info from format

                    if (pssc.SearchType == StructureSearchType.Substructure)
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for highlighting
                        }
                    }

                    else if (pssc.SearchType == StructureSearchType.SmallWorld && pssc.SmallWorldParameters != null)
                    {
                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;
                        HighlightStructureMatches = swp.Highlight;
                        AlignStructureToQuery     = swp.Align;
                        //SmallWorldDepictions = null; // depiction cache
                    }

                    else if (pssc.SearchType == StructureSearchType.Related)                     //
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for SSS highlighting
                        }
                    }

                    else if (sdf.Highlight || sdf.Align)                     // other cases
                    {
                        HighlightStructureMatches = sdf.Highlight;
                        AlignStructureToQuery     = sdf.Align;
                    }

                    else
                    {
                        break;                      // no hilighting / orienting
                    }
                    StructureHighlightQc   = qc;
                    StructureHighlightPssc = pssc;
                } while (false);
            }

            catch (Exception ex)             // log & ignore any errors
            {
                string msg = DebugLog.FormatExceptionMessage(ex);
                if (qc != null)
                {
                    msg += "\r\n" +
                           "Criteria: " + qc.Criteria + "\r\n" +
                           "Molstring: " + qc.MolString;
                }

                DebugLog.Message(msg);
                return;
            }

            // Atom number display (not currently used)

            SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.None;             // see if need to display atom numbers
            for (int ti = 1; ti < Rf.Tables.Count; ti++)
            {
                ResultsTable rt = Rf.Tables[ti];
                MetaTable    mt = rt.MetaTable;
                if (mt.Name.IndexOf("todo: table that needs atom number display") >= 0)
                {
                    SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.All;
                    break;
                }
            }

            StructureHighlightingInitialized = true;
            return;
        }
Example #14
0
        /// <summary>
        /// Scale and translate structure and format into buffer
        /// </summary>
        /// <param name="mol">The structure</param>
        /// <param name="cellStyle">Style/conditional formatting to apply to cell</param>
        /// <param name="commandChar">Command character to use in buffer</param>
        /// <param name="x">Coordinate of left side of structure</param>
        /// <param name="width">Width of molecule box in milliinches</param>
        /// <param name="r">Row in buffer to put on. If less than 0 then return formatted data</param>
        /// <param name="heightInLines">number of lines used</param>

        public FormattedFieldInfo FormatStructure(
            MoleculeMx mol,
            CellStyleMx cellStyle,
            char commandChar,
            int x,
            int width,
            int r,
            ResultsField rfld = null,
            DataRowMx dataRow = null)
        {
            Rectangle destRect, boundingRect;
            int       height;       // formatted  height in milliinches
            bool      markBoundaries;
            int       fixedHeight;
            Bitmap    bm;
            Font      font;
            string    txt, molfile, molString = "", svg, cid = null;
            int       translateType, desiredBondLength = 100;
            int       pixWidth = 0, pixHeight = 0;

            bool debug = DataTableManager.DebugDetails;

            if (debug)
            {
                DebugLog.Message("=============================== FormattingStructure ===============================");
            }
            PerformanceTimer pt      = PT.Start("FormatStructure");
            Stopwatch        swTotal = Stopwatch.StartNew();
            Stopwatch        sw      = Stopwatch.StartNew();

            try
            {
                MoleculeFormat initialCsType  = mol.PrimaryFormat;
                string         initialCsValue = mol.PrimaryValue;

                QueryColumn qc = (rfld != null) ? rfld.QueryColumn : null;

                FormattedFieldInfo ffi = new FormattedFieldInfo();

                if (dataRow != null)                 // get any cid in row
                {
                    int ki = DataTableManager.DefaultKeyValueVoPos;
                    if (ki < dataRow.Length)
                    {
                        cid = dataRow[ki] as string;
                    }
                }

                //DebugLog.Message("FormatStructure " + cid);

                //if (!Rf.Grid) x = x; // debug

                ///////////////////////////////////
                // Highlight structure
                ///////////////////////////////////

                if (StructureHighlightPssc != null)
                {
                    ParsedStructureCriteria pssc = StructureHighlightPssc;

                    // Hilight substructure search match

                    if (pssc.SearchType == StructureSearchType.Substructure ||                     // regular SSS
                        pssc.SearchTypeUnion == StructureSearchType.Substructure)                  // handles related search for just SSS to get hilighting
                    {
                        if (HighlightStructureMatches)
                        {
                            try
                            {
                                mol = StrMatcher.HighlightMatchingSubstructure(mol);
                                if (DebugMx.False)                                 // debug
                                {
                                    //string highlightChildren = mol.MolLib.HighlightChildren;
                                    //Color highlightColor = mol.MolLib.HighlightColor;
                                    if (debug)
                                    {
                                        DebugLog.StopwatchMessage("tHilight", sw);
                                    }
                                }
                            }
                            catch (Exception ex) { ex = ex; }
                        }

                        if (AlignStructureToQuery)
                        {
                            try
                            {
                                mol = StrMatcher.AlignToMatchingSubstructure(mol);
                                if (debug)
                                {
                                    DebugLog.StopwatchMessage("tOrient", sw);
                                }
                            }
                            catch (Exception ex) { ex = ex; }
                        }
                    }

                    // Hilight SmallWorld structure match

                    else if (pssc.SearchType == StructureSearchType.SmallWorld)                     // Hilight SmallWorld structure search results
                    {
                        if (SmallWorldDepictions == null)
                        {
                            SmallWorldDepictions = new SmallWorldDepictions();
                        }

                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;

                        //DebugLog.Message("Depict " + cid + ", Hilight " + swp.Highlight + ", Align " + swp.Align); // + "\r\n" + new StackTrace(true));

                        if ((swp.Highlight || swp.Align) & Lex.IsDefined(cid))                         // call depiction for these
                        {
                            svg = SmallWorldDepictions.GetDepiction(cid, swp.Highlight, swp.Align);

                            if (Lex.IsDefined(svg))                             // have depiction?
                            {
                                {
                                    pixWidth            = MoleculeMx.MilliinchesToPixels(width);
                                    bm                  = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth);
                                    ffi.FormattedBitmap = mol.FormattedBitmap = bm;                                     // store in formatting info and chem structure
                                    return(ffi);
                                }
                            }

                            else if (svg == null)                             // start retrieval of this decpiction type & fall through to get default structure initially
                            {
                                SmallWorldDepictions.StartDepictionRetrieval(Qm, StructureHighlightQc, swp.Highlight, swp.Align);
                            }

                            else
                            {
                            }                                    // tried to get it but failed, fall through to get basic structure
                        }
                    }

                    else if (mol.AltFormDefined("Svg"))                     // svg form exist (e.g. SmallWorld or "related" structure search)?
                    {
                        svg = mol.SvgString;
                        if (Lex.IsDefined(svg))
                        {
                            pixWidth            = MoleculeMx.MilliinchesToPixels(width);
                            bm                  = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth);
                            ffi.FormattedBitmap = mol.FormattedBitmap = bm;                             // store in formatting info and chem structure
                            return(ffi);
                        }
                    }
                }

                ///////////////////////////////////
                // Handle each output device
                ///////////////////////////////////

                ffi.HeightInLines = 1;                 // min of 1 line

                if (Rf.SdFile)
                {
                    FormatSdfileStructure(mol);
                    return(null);
                }

                int pageHeight = 11000;
                if (Rf.PageMargins != null)
                {
                    pageHeight = Rf.PageMargins.Top + Rf.PageHeight + Rf.PageMargins.Bottom;
                }

                if (Rf.Excel || Rf.Word)
                {
                    translateType = 2;
                }
                else
                {
                    translateType = 0;
                }

                if (!Rf.FixedHeightStructures)
                {
                    fixedHeight = 0;                                            // not fixed height
                }
                else if (Rf.Excel || Rf.Word)
                {
                    fixedHeight = 1;                                           // always fixed height
                }
                else
                {
                    fixedHeight = 2;                  // fixed height unless need to expand
                }
                if (Rf.Word && Rf.FixedHeightStructures)
                {
                    markBoundaries = true;
                }
                else
                {
                    markBoundaries = false;
                }

                destRect = new Rectangle(0, 0, width, width * 4 / 5);                 // default dest rect

                ///////////////////////////////////////////////////////////////////////////
                // Tempory fake generation of HELM & associatedimage for biopolymer testing
                ///////////////////////////////////////////////////////////////////////////

                //if (MoleculeMx.HelmEnabled == DebugMx.False) // artificially generate helm molecules
                //	MoleculeMx.SetMoleculeToTestHelmString(mol.GetCorpId().ToString(), mol);

                ///////////////////////////////////////////////////////////////////////////
                // End of tempory fake generation of HELM & associatedimage for biopolymer testing
                ///////////////////////////////////////////////////////////////////////////

                bool fitStructure = true;

                if (mol.IsChemStructureFormat)
                {
                    if (Rf.Grid)                     // special scale for grid
                    {
                        double scale = (float)width / MoleculeMx.StandardBoxWidth;
                        desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale));
                        //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0));
                        desiredBondLength = (int)(desiredBondLength * 90.0 / 100.0);                         // scale down a bit for grid
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tAdjustBondLength1", sw);
                        }
                    }

                    else                     // set desired bond length based on page scaling
                    {
                        float scale = (float)width / MoleculeMx.StandardBoxWidth;
                        desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale));
                        //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0));
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tAdjustBondLength2", sw);
                        }
                    }

                    if (desiredBondLength < 1)
                    {
                        desiredBondLength = 1;
                    }
                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tBeforeFit", sw);
                    }

                    if (fitStructure)
                    {
                        mol.CdkMol.FitStructureIntoRectangle                         // scale and translate structure into supplied rectangle.
                            (ref destRect, desiredBondLength, translateType, fixedHeight, markBoundaries, pageHeight, out boundingRect);
                    }

                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tFitStructure", sw);
                    }

                    ffi.HeightInLines = (int)(destRect.Height / Rf.LineHeight + 1);                     // lines needed
                }

                else if (mol.IsBiopolymerFormat)
                {
                    if (mol.PrimaryFormat == MoleculeFormat.Helm && Rf.Excel)
                    {
                        svg = HelmControl.GetSvg(mol.HelmString);
                        float           inchWidth = width / 1000.0f;               // convert width milliinches to inches
                        Svg.SvgDocument svgDoc    = SvgUtil.AdjustSvgDocumentToFitContent(svg, inchWidth, Svg.SvgUnitType.Inch);
                        RectangleF      svgbb     = svgDoc.Bounds;
                        float           ar        = svgbb.Width / svgbb.Height; // aspect ratio of svg bounding box

                        height            = (int)(width / ar);                  // height in milliinches
                        ffi.HeightInLines = (int)(height / Rf.LineHeight) + 1;  // lines needed

                        destRect = new Rectangle(0, 0, width, height);
                    }
                }

                //////////////////////////
                /// Output to Grid
                //////////////////////////

                if (Rf.Grid)
                {
                    pixWidth  = MoleculeMx.MilliinchesToPixels(destRect.Width);
                    pixHeight = MoleculeMx.MilliinchesToPixels(destRect.Height);

                    if (cellStyle == null)
                    {
                        if (Qm == null || Qm.MoleculeGrid == null)
                        {
                            font = new Font("Tahoma", 8.25f);
                        }
                        else
                        {
                            font = new Font(Qm.MoleculeGrid.Font, FontStyle.Underline);
                        }
                        cellStyle = new CellStyleMx(font, Color.Blue, Color.Empty);
                    }

                    if (mol.IsChemStructureFormat)                     // molfile type molecule
                    {
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tBeforeGetDisplayPreferences", sw);
                        }
                        DisplayPreferences dp = mol.GetDisplayPreferences();
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tGetDisplayPreferences", sw);
                        }

                        //desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange(desiredBondLength); // be sure bond len within allowed range
                        //if (debug) DebugLog.StopwatchMessage("tAdjustBondLengthToValidRange", sw);
                        //dp.StandardBondLength = MoleculeMx.MilliinchesToDecipoints(desiredBondLength);
                        bm = mol.CdkMol.GetFixedHeightMoleculeBitmap(pixWidth, pixHeight, dp, cellStyle, mol.Caption);
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tGetBitmap", sw);
                        }
                    }

                    else if (mol.IsBiopolymerFormat)                     // Output HELM image for biopolymer
                    {
                        pixWidth = MoleculeMx.MilliinchesToPixels(width);
                        bm       = HelmConverter.HelmToBitmap(mol, pixWidth);
                    }

                    else
                    {
                        bm = new Bitmap(1, 1);
                    }

                    ffi.FormattedBitmap = mol.FormattedBitmap = bm;      // store in formatting & structure
                    ffi.FormattedText   = "Formatted";                   // indicate formatted (could save structure string but not needed and avoids possible conversion overhead)
                    return(ffi);
                }

                //////////////////////////
                /// Output to Html
                //////////////////////////

                else if (Rf.Html)
                {
                    if (r >= 0)
                    {
                        AssureTbFree(0, r + ffi.HeightInLines - 1);
                    }

                    if (mol.IsChemStructureFormat)
                    {
                        FormatChemStructureHtml(mol, destRect, width, r);
                    }

                    else if (mol.IsBiopolymerFormat)
                    {
                        FormatBiopolymerStructureHtml(mol, destRect, width, r);
                    }

                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tFormatHtmlStructure", sw);
                    }

                    ffi.FormattedBitmap = mol.FormattedBitmap;
                    ffi.FormattedText   = mol.FormattedText;
                    return(ffi);
                }

                /////////////////////////////////////////////////////////////////
                /// Other format, store Smiles or Helm & any cellStyle in buffer
                /////////////////////////////////////////////////////////////////

                else
                {
                    if (mol.IsChemStructureFormat)
                    {
                        if (Rf.ExportStructureFormat == ExportStructureFormat.Smiles)
                        {
                            molString = mol.GetSmilesString();
                        }
                        else
                        {
                            molString = mol.GetChimeString();                          // use Chime if not smiles
                        }
                    }

                    else if (mol.IsBiopolymerFormat)
                    {
                        molString = mol.PrimaryValue;                         // usually Helm but could be sequence
                    }

                    txt = String.Format("{0} {1} {2} {3} {4} {5} {6}",
                                        x, width, destRect.Left, destRect.Top, destRect.Right, destRect.Bottom, molString);

                    if (cellStyle != null)                     // apply style to cell?
                    {
                        txt += " <CellStyle " + cellStyle.Serialize() + ">";
                    }

                    txt = commandChar + " " + txt + "\t";

                    if (r >= 0)
                    {
                        AssureTbFree(0, r + ffi.HeightInLines - 1);
                        Tb.Lines[r] += txt;                         // put in buffer
                    }

                    else
                    {
                        return(new FormattedFieldInfo(txt));                     // just return formatting
                    }
                }

                return(null);
            }

            catch (Exception ex)
            {
                DebugLog.Message(DebugLog.FormatExceptionMessage(ex));
                return(null);
            }

            finally
            {
                pt.Update();
                int formatCount = pt.Count;
                //ClientLog.Message(pt.ToString() + ", " + cs.GetMolHeader()[2]); // + ", " + new StackTrace(true));
                if (debug)
                {
                    DebugLog.StopwatchMessage("tTotalTime", swTotal);
                }
            }
        }
Example #15
0
        /// <summary>
        /// Setup the options from psc
        /// </summary>
        /// <param name="psc"></param>

        public void Setup(
            SmallWorldPredefinedParameters swpArg)
        {
            try
            {
                InSetup = true;
                bool t = true, f = false;

                Swp = swpArg;                 // save reference to parameters

                if (SwDbDict == null)
                {
                    SwDbDict = DictionaryMx.Get("SmallWorldDatabases");
                    if (SwDbDict != null)
                    {
                        UIMisc.SetListControlItemsFromDictionary(DatabaseComboBox.Properties.Items, SwDbDict.Name, true);
                    }

                    GetDefaultSmallWorldOptions();                     // also get any default options for user
                }

                if (Swp == null)                 // get initial option values
                {
                    SmallWorldPredefinedParameters swp = FindStandardPresetMatchingCustomSettings();

                    if (swp == null)                     // if no match then use my preferred
                    {
                        swp = CustomSettings;
                    }

                    if (swp.MaxHits <= 0)                     // be sure maxhits is defined
                    {
                        swp.MaxHits = SmallWorldPredefinedParameters.DefaultMaxHits;
                    }

                    Swp = swp.Clone();                     // make copy
                }

                List <string> dbList = GetDbSetList();

                string dbs           = "";
                foreach (string dbName in dbList)
                {
                    if (SwDbDict.LookupDefinition(dbName) == null)
                    {
                        continue;
                    }
                    if (dbs != "")
                    {
                        dbs += ", ";
                    }
                    dbs += dbName;
                }

                Swp.Database = dbs;

                if (Lex.IsUndefined(Swp.Database))                 // default to first entry in dict
                {
                    Swp.Database = SwDbDict.Words[0];              // assign first database as default if not defined
                }
                DatabaseComboBox.Text = Swp.Database;

                PresetsComboBox.Text = Swp.PresetName;

                CriteriaStructureRangeCtl.SetRange(DistanceRange, "", DistanceRangeLabel, null, Swp.Distance);
                if (Swp.MaxHits < 0)
                {
                    MaxHits.Text = "";
                }
                else
                {
                    MaxHits.Text = Swp.MaxHits.ToString();
                }

                // Set the Defined and Enabled attributes for each range based on search type

                Swp.TerminalUp.Enabled        = Swp.TerminalDown.Enabled = true;
                Swp.RingUp.Enabled            = Swp.RingDown.Enabled = true;
                Swp.LinkerUp.Enabled          = Swp.LinkerDown.Enabled = true;
                Swp.MutationMinor.Enabled     = Swp.MutationMajor.Enabled = true;
                Swp.SubstitutionRange.Enabled = Swp.HybridisationChange.Enabled = true;

                if (Lex.Eq(Swp.PresetName, SmallWorld.PresetName) ||
                    Lex.Eq(Swp.PresetName, CustomSettings.PresetName))
                {
                    ;
                }

                else if (Lex.Eq(Swp.PresetName, Substructure.PresetName))
                {
                    Swp.TerminalDown.Enabled = false;
                    Swp.RingDown.Enabled     = false;
                    Swp.LinkerDown.Enabled   = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, SuperStructure.PresetName))
                {
                    Swp.TerminalUp.Enabled = false;
                    Swp.RingUp.Enabled     = false;
                    Swp.LinkerUp.Enabled   = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, BemisMurckoFramework.PresetName))
                {
                    Swp.RingUp.Enabled   = Swp.RingDown.Enabled = false;
                    Swp.LinkerUp.Enabled = Swp.LinkerDown.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, NqMCS.PresetName))
                {
                    Swp.LinkerUp.Enabled      = Swp.LinkerDown.Enabled = false;
                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                else if (Lex.Eq(Swp.PresetName, ElementGraph.PresetName))
                {
                    Swp.TerminalUp.Enabled = Swp.TerminalDown.Enabled = false;
                    Swp.RingUp.Enabled     = Swp.RingDown.Enabled = false;
                    Swp.LinkerUp.Enabled   = Swp.LinkerDown.Enabled = false;

                    Swp.MutationMinor.Enabled = Swp.MutationMajor.Enabled = false;
                }

                MatchAtomTypes.Checked = Swp.MatchAtomTypes;
                bool e = Swp.MatchAtomTypes;
                Swp.LinkerUp.Active          = Swp.LinkerDown.Active = !e;
                Swp.MutationMinor.Active     = Swp.MutationMajor.Active = e;
                Swp.SubstitutionRange.Active = Swp.HybridisationChange.Active = e;

                // Set the range controls

                TerminalRangeUp.Set(Swp.TerminalUp);
                TerminalRangeDown.Set(Swp.TerminalDown);
                RingRangeUp.Set(Swp.RingUp);
                RingRangeDown.Set(Swp.RingDown);
                LinkerRangeUp.Set(Swp.LinkerUp);
                LinkerRangeDown.Set(Swp.LinkerDown);

                MutationRangeMinor.Set(Swp.MutationMinor);
                MutationRangeMajor.Set(Swp.MutationMajor);
                SubstitutionRange.Set(Swp.SubstitutionRange);
                HybridizationRange.Set(Swp.HybridisationChange);

                ShowColors.Checked = Swp.Highlight;
                SetControlBackgroundColors(ShowColors.Checked);

                AlignStructs.Checked = Swp.Align;
            }

            finally { InSetup = false; }

            return;
        }