import * as DG from 'datagrok-api/dg'; import * as ui from 'datagrok-api/ui'; import * as grok from 'datagrok-api/grok'; import $ from 'cash-dom'; import { MARVIN_MOLV2000, MARVIN_MOLV3000, MARVIN_SMARTS, MARVIN_SMILES } from './constants'; import { Subject, Subscription } from 'rxjs'; let marvinId = 1; let marvinRoot: any = null; export let _package = new DG.Package(); export let _properties: any; const marvinUploaded = new Subject(); const SERVICES_PROPS_MAPPING: {[key: string]: string} = { 'MolConvertPath': 'molconvertws', 'Clean2dPath': 'clean2dws', 'Clean3dPath': 'clean3dws', 'StereoInfoPath': 'stereoinfows', 'ReactionConvertPath': 'reactionconvertws', 'HydrogenizePath': 'hydrogenizews', 'AutoMapperPath': 'automapperws', 'AromatizePath': 'aromatizews', } //tags: init export async function initMarvin() { marvinRoot = _package.webRoot; _properties = await _package.getProperties(); //@ts-ignore window['refreshMarvin'] = (sketchId: string) => marvinUploaded.next(sketchId); } //name: Marvin //tags: moleculeSketcher //output: widget sketcher export function marvinSketcher() { return new MarvinSketcher(); } /** * See details: https://docs.chemaxon.com/display/docs/how-to-embed.md * */ class MarvinSketcher extends grok.chem.SketcherBase { iframe?: HTMLIFrameElement; _smiles: string | null = null; _molV2000: string | null = null; _molV3000: string | null = null; _smarts: string | null = null; _sketcher: any = null; refreshing = false; _importing = false; hostId = ''; refreshSub: Subscription | null = null; init(host: any) { if (!this.root.childElementCount) { this.refreshSub?.unsubscribe(); this.host = host; var params = new URLSearchParams(); params.append("licPath", _properties.LicensePath); let sketchId = `marvin-${marvinId++}`; params.append("sketchId", sketchId); _package.logger.debug(`creating marvin with id: ${sketchId}`); this.iframe = document.createElement('iframe'); this.iframe.style.border = 'none'; this.iframe.src = `${marvinRoot}marvin/editor.html` + '?' + params.toString(); this.iframe.id = sketchId; this.root.appendChild(this.iframe); this.hostId = `host_${sketchId}`; this.root.id = this.hostId; let e = this; //@ts-ignore return window.MarvinJSUtil.getEditor(sketchId) .then(function (sketcherInstance: any) { sketcherInstance.setDisplaySettings({ toolbars: 'markush' }) e.initSketcher(sketcherInstance); _package.logger.debug(`Marvin with id ${sketchId} created`); $(e.iframe).contents().find("head").append($("")); e.refreshSub = marvinUploaded.subscribe((id: string) => { if (sketchId === id) e.refresh(); }) }.bind(this) , function (error: string) { grok.shell.error(`Loading of the sketcher failed: ${error}`); }); } } // This is needed because for some reason, when reusing the sketcher and moving it between DOM elements // we stop getting events from it. refresh() { _package.logger.debug(`in Marvin refresh ${this.molFile}`); let molFile = this.molFile; this.iframe?.remove(); if (!this.host) return; ui.tools.waitForElementInDom(this.host.root) .then((_) => this.init(this.host)) .then((_) => { _package.logger.debug(`in Marvin refresh then ${molFile}`); this.refreshing = true; this.molFile = molFile; }); } enableServices() { const services: {[key: string]: string} = {}; Object.keys(SERVICES_PROPS_MAPPING).forEach((key) => { if (_properties[key] != null && _properties[key] !== '') services[SERVICES_PROPS_MAPPING[key]] = _properties[key]; }); if (Object.keys(services).length) this._sketcher?.setServices(services); } initSketcher(sketcher: any) { this._sketcher = sketcher; this.enableServices(); _package.logger.debug(`in Marvin initSketcher, enabledServices`); sketcher.on('molchange', async () => { _package.logger.debug(`in Marvin molchange`); // Reset explicitMol only on a real user edit, not on our own importStructure. // _importing is set by smiles/molFile/molV3000 setters; the cache-guard matches Ketcher: // skip the reset on the very first molchange after construction when nothing is cached yet. if (this._importing) { this._importing = false; } else if (this._smiles !== null || this._molV2000 !== null || this._molV3000 !== null || this._smarts !== null) { this.explicitMol = null; } //setting molv2000 try { this._molV2000 = this.sketcherDialogOpened() || this.host?._mode === DG.chem.SKETCHER_MODE.INPLACE ? await this.promiseWithTimeout(this._sketcher.exportStructure(MARVIN_MOLV2000), 3000, new Error('Exporting molv2000 timeout')) : this._molV2000; } catch (e: any) { _package.logger.debug(e.message); this._molV2000 = null; } _package.logger.debug(`in Marvin molchange, set molv2000: ${this._molV2000}`); //setting molv3000 try { if (_properties.MolConvertPath == '') { _package.logger.debug(`in Marvin molchange without MolConvertPath, setting molv3000`); this._molV3000 = this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.V3KMolBlock) : null; _package.logger.debug(`in Marvin molchange without MolConvertPath, set molv3000: ${this._molV3000}`); } else { _package.logger.debug(`in Marvin molchange with MolConvertPath, setting molv3000`); this._molV3000 = this.sketcherDialogOpened() || this.host?._mode === DG.chem.SKETCHER_MODE.INPLACE ? await this.promiseWithTimeout(this._sketcher.exportStructure(MARVIN_MOLV3000), 3000, new Error('Exporting molv3000 timeout')) : this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.V3KMolBlock) : null; _package.logger.debug(`in Marvin molchange with MolConvertPath, set molv3000: ${this._molV3000}`); } } catch (e: any) { _package.logger.debug(e.message); this._molV3000 = e.message === 'Exporting molv3000 timeout' && this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.V3KMolBlock) : null; } //setting smiles try { if (_properties.MolConvertPath == '') { _package.logger.debug(`in Marvin molchange without MolConvertPath, setting smiles`); this._smiles = this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smiles) : null; _package.logger.debug(`in Marvin molchange without MolConvertPath, set smiles: ${this._smiles}`); } else { _package.logger.debug(`in Marvin molchange with MolConvertPath, setting smiles`); this._smiles = this.sketcherDialogOpened() || this.host?._mode === DG.chem.SKETCHER_MODE.INPLACE ? await this.promiseWithTimeout(this._sketcher.exportStructure(MARVIN_SMILES), 3000, new Error('Exporting smiles timeout')) : this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smiles) : null; _package.logger.debug(`in Marvin molchange with MolConvertPath, set smiles: ${this._smiles}`); } } catch (e: any) { _package.logger.debug(e.message); try { this._smiles = e.message === 'Exporting smiles timeout' && this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smiles) : null; } catch { // in case for instance we try to convert query to smiles we will get an exception this._smiles = null; } } //setting smarts try { if (_properties.MolConvertPath == '') { _package.logger.debug(`in Marvin molchange without MolConvertPath, setting smarts, mol: ${this._molV2000}`); this._smarts = this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smarts) : null; _package.logger.debug(`in Marvin molchange without MolConvertPath, set smarts: ${this._smarts}`); } else { _package.logger.debug(`in Marvin molchange with MolConvertPath, setting smarts`); this._smarts = this.sketcherDialogOpened() || this.host?._mode === DG.chem.SKETCHER_MODE.INPLACE? await this.promiseWithTimeout(this._sketcher.exportStructure(MARVIN_SMARTS), 3000, new Error('Exporting smarts timeout')) : this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smarts) : null; _package.logger.debug(`in Marvin molchange with MolConvertPath, set smarts: ${this._smarts}`); } } catch (e: any) { _package.logger.debug(e.message); this._smarts = e.message === 'Exporting smarts timeout' && this._molV2000 ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smarts) : null; } _package.logger.debug(`in Marvin molchange finishing, refreshing: ${this.refreshing}`); if (this.refreshing) this.refreshing = false; else this.onChanged.next(null); }); } sketcherDialogOpened(): boolean { return document.getElementById(this.hostId) !== null; } get supportedExportFormats() { return ['smiles', 'mol', 'smarts']; } async getSmarts() { _package.logger.debug(`in Marvin async getSmarts`); const smarts = this._smarts === null ? this._molV2000 !== null ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smarts) : this._molV3000 !== null ? DG.chem.convert(this._molV3000, DG.chem.Notation.V3KMolBlock, DG.chem.Notation.Smarts) : this._smiles !== null ? DG.chem.convert(this._smiles, DG.chem.Notation.Smiles, DG.chem.Notation.Smarts) : '' : this._smarts; _package.logger.debug(`in Marvin get smarts, returning ${smarts}`); return smarts; } set smarts(s: string) { this._smarts = s; this._smiles = null; this._molV2000 = null; this._molV3000 = null; if (_properties.MolConvertPath == '') { _package.logger.debug(`in Marvin set smarts without MolConvertPath, ${s}`); this.convertAndSetSmarts(s); _package.logger.debug(`in Marvin set smarts without MolConvertPath, done`); } else { _package.logger.debug(`in Marvin set smarts with MolConvertPath, ${s}`); this._sketcher?.importStructure(MARVIN_SMARTS, s); _package.logger.debug(`in Marvin set smarts with MolConvertPath, done`); } } get smiles() { _package.logger.debug(`in Marvin get smiles`); if (this.explicitMol?.notation === 'smiles') return this.explicitMol.value; const smiles = this._smiles === null ? this._molV2000 !== null ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.Smiles) : this._molV3000 !== null ? DG.chem.convert(this._molV3000, DG.chem.Notation.V3KMolBlock, DG.chem.Notation.Smiles) : this._smarts !== null ? DG.chem.smilesFromSmartsWarning() : '' : this._smiles; _package.logger.debug(`in Marvin get smiles, returning ${smiles}`); return smiles; } set smiles(s: string) { this._smiles = s; this._molV2000 = null; this._molV3000 = null; this._smarts = null; this.explicitMol = s === '' ? null : {notation: 'smiles', value: s}; this._importing = true; if (_properties.MolConvertPath == '' || s === '') { _package.logger.debug(`in Marvin set smiles without MolConvertPath, ${s}`); const mol = DG.chem.convert(s, DG.chem.Notation.Smiles, DG.chem.Notation.MolBlock); _package.logger.debug(`in Marvin set smiles without MolConvertPath, mol: ${mol}`); this._sketcher?.importStructure(MARVIN_MOLV2000, mol); _package.logger.debug(`in Marvin set smiles without MolConvertPath, done`); } else { _package.logger.debug(`in Marvin set smiles with MolConvertPath, ${s}`); this._sketcher?.importStructure(MARVIN_SMILES, s); _package.logger.debug(`in Marvin set smiles with MolConvertPath, done`); } } get molFile() { _package.logger.debug(`in Marvin get molFile`); if (this.explicitMol?.notation === 'molblock') return this.explicitMol.value; const mol = this._molV2000 === null ? this._molV3000 !== null ? DG.chem.convert(this._molV3000, DG.chem.Notation.V3KMolBlock, DG.chem.Notation.MolBlock) : this._smiles !== null ? DG.chem.convert(this._smiles, DG.chem.Notation.Smiles, DG.chem.Notation.MolBlock) : this._smarts !== null ? DG.chem.convert(this._smarts, DG.chem.Notation.Smarts, DG.chem.Notation.MolBlock) : '' : this._molV2000; _package.logger.debug(`in Marvin get molFile, done, mol: ${mol}`); return mol; } set molFile(s: string) { this._molV2000 = s === '' ? DG.WHITE_MOLBLOCK : s; this._molV3000 = null; this._smiles = null; this._smarts = null; this.explicitMol = s === '' ? null : {notation: 'molblock', value: s}; this._importing = true; _package.logger.debug(`in Marvin set molFile, mol: ${s}`); this._sketcher?.importStructure(MARVIN_MOLV2000, this._molV2000); _package.logger.debug(`in Marvin set molFile, done`); } get molV3000() { _package.logger.debug(`in Marvin get molV3000`); if (this.explicitMol?.notation === 'molblockV3000') return this.explicitMol.value; const mol = this._molV3000 === null ? this._molV2000 !== null ? DG.chem.convert(this._molV2000, DG.chem.Notation.MolBlock, DG.chem.Notation.V3KMolBlock) : this._smiles !== null ? DG.chem.convert(this._smiles, DG.chem.Notation.Smiles, DG.chem.Notation.V3KMolBlock) : this._smarts !== null ? DG.chem.convert(this._smarts, DG.chem.Notation.Smarts, DG.chem.Notation.V3KMolBlock) : '' : this._molV3000; _package.logger.debug(`in Marvin get molV3000, done, mol: ${mol}`); return mol; } set molV3000(s: string) { this._molV3000 = s; this._molV2000 = null; this._smiles = null; this._smarts = null; this.explicitMol = s === '' ? null : {notation: 'molblockV3000', value: s}; this._importing = true; if (_properties.MolConvertPath == '') { _package.logger.debug(`in Marvin set molv3000 without MolConvertPath, ${s}`); const mol = DG.chem.convert(s, DG.chem.Notation.V3KMolBlock, DG.chem.Notation.MolBlock); _package.logger.debug(`in Marvin set molv3000 without MolConvertPath, mol: ${mol}`); this._sketcher?.importStructure(MARVIN_MOLV2000, mol); _package.logger.debug(`in Marvin set molv3000 without MolConvertPath, done`); } else { _package.logger.debug(`in Marvin set molv3000 with MolConvertPath, ${s}`); this._sketcher?.importStructure(MARVIN_MOLV3000, s); _package.logger.debug(`in Marvin set molv3000 with MolConvertPath, done`); } } get isInitialized() { return this._sketcher !== null; } private convertAndSetSmarts(s: string) { _package.logger.debug(`in Marvin convertAndSetSmarts, ${s}`); //in case we have a real smarts not a molblock with query features if (!DG.chem.isMolBlock(s)) s = DG.chem.convert(s, DG.chem.Notation.Smarts, DG.chem.Notation.MolBlock); this._sketcher?.importStructure(MARVIN_MOLV2000, s); _package.logger.debug(`in Marvin convertAndSetSmarts, done`); } private promiseWithTimeout( promise: Promise, ms: number, timeoutError = new Error('Promise timed out') ): Promise { let timer: number | undefined; const timeout = new Promise((_, reject) => { const interval = 100; let totalTime = 0; timer = window.setInterval(() => { totalTime += interval; if ((!this.sketcherDialogOpened() && this.host?._mode === DG.chem.SKETCHER_MODE.EXTERNAL) || totalTime > ms) { _package.logger.debug(`in Marvin promiseWithTimeout -> dialog closed`); window.clearInterval(timer); reject(timeoutError); } }, interval); }); return Promise.race([promise, timeout]) .finally(() => { if (timer !== undefined) window.clearInterval(timer); }); } }