UNPKG

molstar

Version:

A comprehensive macromolecular library.

506 lines (505 loc) 27.2 kB
"use strict"; /** * Copyright (c) 2018-2022 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author David Sehnal <david.sehnal@gmail.com> * @author Alexander Rose <alexander.rose@weirdbyte.de> */ Object.defineProperty(exports, "__esModule", { value: true }); exports.PluginContext = void 0; var tslib_1 = require("tslib"); var immer_1 = tslib_1.__importStar(require("immer")); var immutable_1 = require("immutable"); var rxjs_1 = require("rxjs"); var operators_1 = require("rxjs/operators"); var canvas3d_1 = require("../mol-canvas3d/canvas3d"); var util_1 = require("../mol-canvas3d/util"); var linear_algebra_1 = require("../mol-math/linear-algebra"); var custom_property_1 = require("../mol-model-props/common/custom-property"); var data_1 = require("../mol-plugin-state/builder/data"); var structure_1 = require("../mol-plugin-state/builder/structure"); var registry_1 = require("../mol-plugin-state/formats/registry"); var structure_selection_query_1 = require("../mol-plugin-state/helpers/structure-selection-query"); var animation_1 = require("../mol-plugin-state/manager/animation"); var camera_1 = require("../mol-plugin-state/manager/camera"); var interactivity_1 = require("../mol-plugin-state/manager/interactivity"); var loci_label_1 = require("../mol-plugin-state/manager/loci-label"); var snapshots_1 = require("../mol-plugin-state/manager/snapshots"); var component_1 = require("../mol-plugin-state/manager/structure/component"); var focus_1 = require("../mol-plugin-state/manager/structure/focus"); var hierarchy_1 = require("../mol-plugin-state/manager/structure/hierarchy"); var measurement_1 = require("../mol-plugin-state/manager/structure/measurement"); var selection_1 = require("../mol-plugin-state/manager/structure/selection"); var hierarchy_2 = require("../mol-plugin-state/manager/volume/hierarchy"); var layout_1 = require("./layout"); var representation_1 = require("../mol-repr/representation"); var registry_2 = require("../mol-repr/structure/registry"); var registry_3 = require("../mol-repr/volume/registry"); var mol_state_1 = require("../mol-state"); var mol_task_1 = require("../mol-task"); var color_1 = require("../mol-theme/color"); var size_1 = require("../mol-theme/size"); var assets_1 = require("../mol-util/assets"); var color_2 = require("../mol-util/color"); var data_source_1 = require("../mol-util/data-source"); var debug_1 = require("../mol-util/debug"); var input_observer_1 = require("../mol-util/input/input-observer"); var log_entry_1 = require("../mol-util/log-entry"); var object_1 = require("../mol-util/object"); var rx_event_helper_1 = require("../mol-util/rx-event-helper"); var animation_loop_1 = require("./animation-loop"); var behavior_1 = require("./behavior"); var behavior_2 = require("./behavior/behavior"); var command_1 = require("./command"); var commands_1 = require("./commands"); var config_1 = require("./config"); var state_1 = require("./state"); var substructure_parent_helper_1 = require("./util/substructure-parent-helper"); var task_manager_1 = require("./util/task-manager"); var toast_1 = require("./util/toast"); var viewport_screenshot_1 = require("./util/viewport-screenshot"); var version_1 = require("./version"); var constants_1 = require("../mol-model/structure/structure/carbohydrates/constants"); var PluginContext = /** @class */ (function () { function PluginContext(spec) { var _this = this; var _a; this.spec = spec; this.runTask = function (task, params) { return _this.managers.task.run(task, params); }; this.resolveTask = function (object) { if (!object) return void 0; if (mol_task_1.Task.is(object)) return _this.runTask(object); return object; }; this.subs = []; this.initCanvas3dPromiseCallbacks = [function () { }, function () { }]; this.disposed = false; this.canvasContainer = void 0; this.ev = rx_event_helper_1.RxEventHelper.create(); this.config = new config_1.PluginConfigManager(this.spec.config); // needed to init state this.state = new state_1.PluginState(this); this.commands = new command_1.PluginCommandManager(); this.canvas3dInit = this.ev.behavior(false); this.behaviors = { state: { isAnimating: this.ev.behavior(false), isUpdating: this.ev.behavior(false), // TODO: should there be separate "updated" event? // Often, this is used to indicate that the state has updated // and it might not be the best way to react to state updates. isBusy: this.ev.behavior(false) }, interaction: { hover: this.ev.behavior({ current: representation_1.Representation.Loci.Empty, modifiers: input_observer_1.ModifiersKeys.None, buttons: 0, button: 0 }), click: this.ev.behavior({ current: representation_1.Representation.Loci.Empty, modifiers: input_observer_1.ModifiersKeys.None, buttons: 0, button: 0 }), drag: this.ev.behavior({ current: representation_1.Representation.Loci.Empty, modifiers: input_observer_1.ModifiersKeys.None, buttons: 0, button: 0, pageStart: (0, linear_algebra_1.Vec2)(), pageEnd: (0, linear_algebra_1.Vec2)() }), selectionMode: this.ev.behavior(false) }, labels: { highlight: this.ev.behavior({ labels: [] }) }, layout: { leftPanelTabName: this.ev.behavior('root') }, canvas3d: { // TODO: remove in 4.0? initialized: this.canvas3dInit.pipe((0, operators_1.filter)(function (v) { return !!v; }), (0, operators_1.take)(1)) } }; this.canvas3dInitialized = new Promise(function (res, rej) { _this.initCanvas3dPromiseCallbacks = [res, rej]; }); this.layout = new layout_1.PluginLayout(this); this.animationLoop = new animation_loop_1.PluginAnimationLoop(this); this.representation = { structure: { registry: new registry_2.StructureRepresentationRegistry(), themes: { colorThemeRegistry: color_1.ColorTheme.createRegistry(), sizeThemeRegistry: size_1.SizeTheme.createRegistry() }, }, volume: { registry: new registry_3.VolumeRepresentationRegistry(), themes: { colorThemeRegistry: color_1.ColorTheme.createRegistry(), sizeThemeRegistry: size_1.SizeTheme.createRegistry() } } }; this.query = { structure: { registry: new structure_selection_query_1.StructureSelectionQueryRegistry() } }; this.dataFormats = new registry_1.DataFormatRegistry(); this.builders = { data: new data_1.DataBuilder(this), structure: void 0 }; this.helpers = { substructureParent: new substructure_parent_helper_1.SubstructureParentHelper(this), viewportScreenshot: void 0 }; this.managers = { structure: { hierarchy: new hierarchy_1.StructureHierarchyManager(this), component: new component_1.StructureComponentManager(this), measurement: new measurement_1.StructureMeasurementManager(this), selection: new selection_1.StructureSelectionManager(this), focus: new focus_1.StructureFocusManager(this), }, volume: { hierarchy: new hierarchy_2.VolumeHierarchyManager(this) }, interactivity: void 0, camera: new camera_1.CameraManager(this), animation: new animation_1.PluginAnimationManager(this), snapshot: new snapshots_1.PluginStateSnapshotManager(this), lociLabels: void 0, toast: new toast_1.PluginToastManager(this), asset: new assets_1.AssetManager(), task: new task_manager_1.TaskManager() }; this.events = { log: this.ev(), task: this.managers.task.events, canvas3d: { settingsUpdated: this.ev(), } }; this.customModelProperties = new custom_property_1.CustomProperty.Registry(); this.customStructureProperties = new custom_property_1.CustomProperty.Registry(); this.customStructureControls = new Map(); this.customImportControls = new Map(); this.genericRepresentationControls = new Map(); /** * Used to store application specific custom state which is then available * to State Actions and similar constructs via the PluginContext. */ this.customState = Object.create(null); this.log = { entries: (0, immutable_1.List)(), entry: function (e) { return _this.events.log.next(e); }, error: function (msg) { return _this.events.log.next(log_entry_1.LogEntry.error(msg)); }, message: function (msg) { return _this.events.log.next(log_entry_1.LogEntry.message(msg)); }, info: function (msg) { return _this.events.log.next(log_entry_1.LogEntry.info(msg)); }, warn: function (msg) { return _this.events.log.next(log_entry_1.LogEntry.warning(msg)); }, }; /** * This should be used in all transform related request so that it could be "spoofed" to allow * "static" access to resources. */ this.fetch = data_source_1.ajaxGet; // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel) // and freezing the params object causes "read-only exception" // TODO: is this the best place to do it? (0, immer_1.setAutoFreeze)(false); (0, constants_1.setSaccharideCompIdMapType)((_a = this.config.get(config_1.PluginConfig.Structure.SaccharideCompIdMapType)) !== null && _a !== void 0 ? _a : 'default'); } PluginContext.prototype.build = function () { return this.state.data.build(); }; PluginContext.prototype.initContainer = function (canvas3dContext) { if (this.canvasContainer) return true; var container = document.createElement('div'); Object.assign(container.style, { position: 'absolute', left: 0, top: 0, right: 0, bottom: 0, '-webkit-user-select': 'none', 'user-select': 'none', '-webkit-tap-highlight-color': 'rgba(0,0,0,0)', '-webkit-touch-callout': 'none', 'touch-action': 'manipulation', }); var canvas = canvas3dContext === null || canvas3dContext === void 0 ? void 0 : canvas3dContext.canvas; if (!canvas) { canvas = document.createElement('canvas'); Object.assign(canvas.style, { 'background-image': 'linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%, lightgrey), linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%, lightgrey)', 'background-size': '60px 60px', 'background-position': '0 0, 30px 30px' }); container.appendChild(canvas); } if (!this.initViewer(canvas, container, canvas3dContext)) { return false; } this.canvasContainer = container; return true; }; PluginContext.prototype.mount = function (target) { var _a; if (this.disposed) throw new Error('Cannot mount a disposed context'); if (!this.initContainer()) return false; if (this.canvasContainer.parentElement !== target) { (_a = this.canvasContainer.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(this.canvasContainer); } target.appendChild(this.canvasContainer); this.handleResize(); return true; }; PluginContext.prototype.unmount = function () { var _a, _b; (_b = (_a = this.canvasContainer) === null || _a === void 0 ? void 0 : _a.parentElement) === null || _b === void 0 ? void 0 : _b.removeChild(this.canvasContainer); }; PluginContext.prototype.initViewer = function (canvas, container, canvas3dContext) { var _this = this; var _a, _b, _c, _d, _e, _f, _g; try { this.layout.setRoot(container); if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial); if (canvas3dContext) { this.canvas3dContext = canvas3dContext; } else { var antialias = !((_a = this.config.get(config_1.PluginConfig.General.DisableAntialiasing)) !== null && _a !== void 0 ? _a : false); var preserveDrawingBuffer = !((_b = this.config.get(config_1.PluginConfig.General.DisablePreserveDrawingBuffer)) !== null && _b !== void 0 ? _b : false); var pixelScale = this.config.get(config_1.PluginConfig.General.PixelScale) || 1; var pickScale = this.config.get(config_1.PluginConfig.General.PickScale) || 0.25; var pickPadding = (_c = this.config.get(config_1.PluginConfig.General.PickPadding)) !== null && _c !== void 0 ? _c : 1; var enableWboit = this.config.get(config_1.PluginConfig.General.EnableWboit) || false; var enableDpoit = this.config.get(config_1.PluginConfig.General.EnableDpoit) || false; var preferWebGl1 = this.config.get(config_1.PluginConfig.General.PreferWebGl1) || false; var failIfMajorPerformanceCaveat = !((_d = this.config.get(config_1.PluginConfig.General.AllowMajorPerformanceCaveat)) !== null && _d !== void 0 ? _d : false); this.canvas3dContext = canvas3d_1.Canvas3DContext.fromCanvas(canvas, this.managers.asset, { antialias: antialias, preserveDrawingBuffer: preserveDrawingBuffer, pixelScale: pixelScale, pickScale: pickScale, pickPadding: pickPadding, enableWboit: enableWboit, enableDpoit: enableDpoit, preferWebGl1: preferWebGl1, failIfMajorPerformanceCaveat: failIfMajorPerformanceCaveat }); } this.canvas3d = canvas3d_1.Canvas3D.create(this.canvas3dContext); this.canvas3dInit.next(true); var props = this.spec.canvas3d; var backgroundColor_1 = (0, color_2.Color)(0xFCFBF9); if (!props) { (_e = this.canvas3d) === null || _e === void 0 ? void 0 : _e.setProps({ renderer: { backgroundColor: backgroundColor_1 } }); } else { if (((_f = props.renderer) === null || _f === void 0 ? void 0 : _f.backgroundColor) === void 0) { props = (0, immer_1.default)(props, function (p) { if (p.renderer) p.renderer.backgroundColor = backgroundColor_1; else p.renderer = { backgroundColor: backgroundColor_1 }; }); } (_g = this.canvas3d) === null || _g === void 0 ? void 0 : _g.setProps(props); } this.animationLoop.start(); this.helpers.viewportScreenshot = new viewport_screenshot_1.ViewportScreenshotHelper(this); this.subs.push(this.canvas3d.interaction.click.subscribe(function (e) { return _this.behaviors.interaction.click.next(e); })); this.subs.push(this.canvas3d.interaction.drag.subscribe(function (e) { return _this.behaviors.interaction.drag.next(e); })); this.subs.push(this.canvas3d.interaction.hover.subscribe(function (e) { return _this.behaviors.interaction.hover.next(e); })); this.subs.push(this.canvas3d.input.resize.subscribe(function () { return _this.handleResize(); })); this.subs.push(this.layout.events.updated.subscribe(function () { return requestAnimationFrame(function () { return _this.handleResize(); }); })); this.handleResize(); mol_task_1.Scheduler.setImmediate(function () { return _this.initCanvas3dPromiseCallbacks[0](); }); return true; } catch (e) { this.log.error('' + e); console.error(e); mol_task_1.Scheduler.setImmediate(function () { return _this.initCanvas3dPromiseCallbacks[1](e); }); return false; } }; PluginContext.prototype.handleResize = function () { var _a, _b; var canvas = (_a = this.canvas3dContext) === null || _a === void 0 ? void 0 : _a.canvas; var container = this.layout.root; if (container && canvas) { var pixelScale = this.config.get(config_1.PluginConfig.General.PixelScale) || 1; (0, util_1.resizeCanvas)(canvas, container, pixelScale); (_b = this.canvas3d) === null || _b === void 0 ? void 0 : _b.requestResize(); } }; Object.defineProperty(PluginContext.prototype, "isBusy", { /** return true is animating or updating */ get: function () { return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value; }, enumerable: false, configurable: true }); Object.defineProperty(PluginContext.prototype, "selectionMode", { get: function () { return this.behaviors.interaction.selectionMode.value; }, set: function (mode) { this.behaviors.interaction.selectionMode.next(mode); }, enumerable: false, configurable: true }); PluginContext.prototype.dataTransaction = function (f, options) { return this.runTask(this.state.data.transaction(f, options)); }; PluginContext.prototype.clear = function (resetViewportSettings) { var _a; if (resetViewportSettings === void 0) { resetViewportSettings = false; } if (resetViewportSettings) (_a = this.canvas3d) === null || _a === void 0 ? void 0 : _a.setProps(canvas3d_1.DefaultCanvas3DParams); return commands_1.PluginCommands.State.RemoveObject(this, { state: this.state.data, ref: mol_state_1.StateTransform.RootRef }); }; PluginContext.prototype.dispose = function (options) { var _a, _b; if (this.disposed) return; for (var _i = 0, _c = this.subs; _i < _c.length; _i++) { var s = _c[_i]; s.unsubscribe(); } this.subs = []; this.commands.dispose(); (_a = this.canvas3d) === null || _a === void 0 ? void 0 : _a.dispose(); (_b = this.canvas3dContext) === null || _b === void 0 ? void 0 : _b.dispose(options); this.ev.dispose(); this.state.dispose(); this.managers.task.dispose(); this.helpers.substructureParent.dispose(); (0, object_1.objectForEach)(this.managers, function (m) { var _a; return (_a = m === null || m === void 0 ? void 0 : m.dispose) === null || _a === void 0 ? void 0 : _a.call(m); }); (0, object_1.objectForEach)(this.managers.structure, function (m) { var _a; return (_a = m === null || m === void 0 ? void 0 : m.dispose) === null || _a === void 0 ? void 0 : _a.call(m); }); this.unmount(); this.canvasContainer = undefined; this.disposed = true; }; PluginContext.prototype.initBehaviorEvents = function () { var _this = this; this.subs.push((0, rxjs_1.merge)(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(function (u) { if (_this.behaviors.state.isUpdating.value !== u) _this.behaviors.state.isUpdating.next(u); })); var timeoutMs = this.config.get(config_1.PluginConfig.General.IsBusyTimeoutMs) || 750; var isBusy = this.behaviors.state.isBusy; var timeout = void 0; var setBusy = function () { if (!isBusy.value) isBusy.next(true); }; var reset = function () { if (timeout !== void 0) clearTimeout(timeout); timeout = void 0; }; this.subs.push((0, rxjs_1.merge)(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(function (v) { var isUpdating = _this.behaviors.state.isUpdating.value; var isAnimating = _this.behaviors.state.isAnimating.value; if (isUpdating || isAnimating) { if (!isBusy.value) { reset(); timeout = setTimeout(setBusy, timeoutMs); } } else { reset(); isBusy.next(false); } })); this.subs.push(this.behaviors.interaction.selectionMode.subscribe(function (v) { var _a; if (!v) { (_a = _this.managers.interactivity) === null || _a === void 0 ? void 0 : _a.lociSelects.deselectAll(); } })); }; PluginContext.prototype.initBuiltInBehavior = function () { var _this = this; behavior_1.BuiltInPluginBehaviors.State.registerDefault(this); behavior_1.BuiltInPluginBehaviors.Representation.registerDefault(this); behavior_1.BuiltInPluginBehaviors.Camera.registerDefault(this); behavior_1.BuiltInPluginBehaviors.Misc.registerDefault(this); this.subs.push((0, rxjs_1.merge)(this.state.data.events.log, this.state.behaviors.events.log).subscribe(function (e) { return _this.events.log.next(e); })); }; PluginContext.prototype.initBehaviors = function () { return tslib_1.__awaiter(this, void 0, void 0, function () { var tree, _i, _a, cat, _b, _c, b, cat, _d, _e, b, cat; return tslib_1.__generator(this, function (_f) { switch (_f.label) { case 0: tree = this.state.behaviors.build(); for (_i = 0, _a = Object.keys(behavior_2.PluginBehavior.Categories); _i < _a.length; _i++) { cat = _a[_i]; tree.toRoot().apply(behavior_2.PluginBehavior.CreateCategory, { label: behavior_2.PluginBehavior.Categories[cat] }, { ref: cat, state: { isLocked: true } }); } // Init custom properties 1st for (_b = 0, _c = this.spec.behaviors; _b < _c.length; _b++) { b = _c[_b]; cat = behavior_2.PluginBehavior.getCategoryId(b.transformer); if (cat !== 'custom-props') continue; tree.to(behavior_2.PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id }); } return [4 /*yield*/, this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }))]; case 1: _f.sent(); tree = this.state.behaviors.build(); for (_d = 0, _e = this.spec.behaviors; _d < _e.length; _d++) { b = _e[_d]; cat = behavior_2.PluginBehavior.getCategoryId(b.transformer); if (cat === 'custom-props') continue; tree.to(behavior_2.PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id }); } return [4 /*yield*/, this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }))]; case 2: _f.sent(); return [2 /*return*/]; } }); }); }; PluginContext.prototype.initCustomFormats = function () { if (!this.spec.customFormats) return; for (var _i = 0, _a = this.spec.customFormats; _i < _a.length; _i++) { var f = _a[_i]; this.dataFormats.add(f[0], f[1]); } }; PluginContext.prototype.initAnimations = function () { if (!this.spec.animations) return; for (var _i = 0, _a = this.spec.animations; _i < _a.length; _i++) { var anim = _a[_i]; this.managers.animation.register(anim); } }; PluginContext.prototype.initDataActions = function () { if (!this.spec.actions) return; for (var _i = 0, _a = this.spec.actions; _i < _a.length; _i++) { var a = _a[_i]; this.state.data.actions.add(a.action); } }; PluginContext.prototype.init = function () { return tslib_1.__awaiter(this, void 0, void 0, function () { var _this = this; return tslib_1.__generator(this, function (_a) { switch (_a.label) { case 0: this.subs.push(this.events.log.subscribe(function (e) { return _this.log.entries = _this.log.entries.push(e); })); this.initCustomFormats(); this.initBehaviorEvents(); this.initBuiltInBehavior(); this.managers.interactivity = new interactivity_1.InteractivityManager(this); this.managers.lociLabels = new loci_label_1.LociLabelManager(this); this.builders.structure = new structure_1.StructureBuilder(this); this.initAnimations(); this.initDataActions(); return [4 /*yield*/, this.initBehaviors()]; case 1: _a.sent(); this.log.message("Mol* Plugin ".concat(version_1.PLUGIN_VERSION, " [").concat(version_1.PLUGIN_VERSION_DATE.toLocaleString(), "]")); if (!debug_1.isProductionMode) this.log.message("Development mode enabled"); if (debug_1.isDebugMode) this.log.message("Debug mode enabled"); return [2 /*return*/]; } }); }); }; return PluginContext; }()); exports.PluginContext = PluginContext;