context.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import produce, { setAutoFreeze } from 'immer';
  8. import { List } from 'immutable';
  9. import { merge } from 'rxjs';
  10. import { Canvas3D, DefaultCanvas3DParams } from '../mol-canvas3d/canvas3d';
  11. import { CustomProperty } from '../mol-model-props/common/custom-property';
  12. import { Model, Structure } from '../mol-model/structure';
  13. import { DataBuilder } from '../mol-plugin-state/builder/data';
  14. import { StructureBuilder } from '../mol-plugin-state/builder/structure';
  15. import { DataFormatRegistry } from '../mol-plugin-state/formats/registry';
  16. import { StructureSelectionQueryRegistry } from '../mol-plugin-state/helpers/structure-selection-query';
  17. import { CameraManager } from '../mol-plugin-state/manager/camera';
  18. import { InteractivityManager } from '../mol-plugin-state/manager/interactivity';
  19. import { LociLabel, LociLabelManager } from '../mol-plugin-state/manager/loci-label';
  20. import { StructureComponentManager } from '../mol-plugin-state/manager/structure/component';
  21. import { StructureFocusManager } from '../mol-plugin-state/manager/structure/focus';
  22. import { StructureHierarchyManager } from '../mol-plugin-state/manager/structure/hierarchy';
  23. import { StructureHierarchyRef } from '../mol-plugin-state/manager/structure/hierarchy-state';
  24. import { StructureMeasurementManager } from '../mol-plugin-state/manager/structure/measurement';
  25. import { StructureSelectionManager } from '../mol-plugin-state/manager/structure/selection';
  26. import { PluginUIComponent } from '../mol-plugin-ui/base';
  27. import { StateTransformParameters } from '../mol-plugin-ui/state/common';
  28. import { Representation } from '../mol-repr/representation';
  29. import { StructureRepresentationRegistry } from '../mol-repr/structure/registry';
  30. import { VolumeRepresentationRegistry } from '../mol-repr/volume/registry';
  31. import { StateTransform } from '../mol-state';
  32. import { Task, RuntimeContext } from '../mol-task';
  33. import { ColorTheme } from '../mol-theme/color';
  34. import { SizeTheme } from '../mol-theme/size';
  35. import { ThemeRegistryContext } from '../mol-theme/theme';
  36. import { Color } from '../mol-util/color';
  37. import { ajaxGet } from '../mol-util/data-source';
  38. import { isDebugMode, isProductionMode } from '../mol-util/debug';
  39. import { ModifiersKeys } from '../mol-util/input/input-observer';
  40. import { LogEntry } from '../mol-util/log-entry';
  41. import { RxEventHelper } from '../mol-util/rx-event-helper';
  42. import { BuiltInPluginBehaviors } from './behavior';
  43. import { PluginBehavior } from './behavior/behavior';
  44. import { PluginCommandManager } from './command';
  45. import { PluginCommands } from './commands';
  46. import { PluginConfig, PluginConfigManager } from './config';
  47. import { LeftPanelTabName, PluginLayout } from './layout';
  48. import { PluginSpec } from './spec';
  49. import { PluginState } from './state';
  50. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  51. import { TaskManager } from './util/task-manager';
  52. import { PluginToastManager } from './util/toast';
  53. import { ViewportScreenshotHelper } from './util/viewport-screenshot';
  54. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  55. import { AssetManager } from '../mol-util/assets';
  56. import { PluginStateSnapshotManager } from '../mol-plugin-state/manager/snapshots';
  57. import { PluginAnimationManager } from '../mol-plugin-state/manager/animation';
  58. import { objectForEach } from '../mol-util/object';
  59. import { VolumeHierarchyManager } from '../mol-plugin-state/manager/volume/hierarchy';
  60. import { filter, take } from 'rxjs/operators';
  61. import { Vec2 } from '../mol-math/linear-algebra';
  62. import { PluginAnimationLoop } from './animation-loop';
  63. export class PluginContext {
  64. runTask = <T>(task: Task<T>) => this.managers.task.run(task);
  65. resolveTask = <T>(object: Task<T> | T | undefined) => {
  66. if (!object) return void 0;
  67. if (Task.is(object)) return this.runTask(object);
  68. return object;
  69. }
  70. private disposed = false;
  71. private ev = RxEventHelper.create();
  72. readonly config = new PluginConfigManager(this.spec.config); // needed to init state
  73. readonly state = new PluginState(this);
  74. readonly commands = new PluginCommandManager();
  75. private canvas3dInit = this.ev.behavior<boolean>(false);
  76. readonly behaviors = {
  77. state: {
  78. isAnimating: this.ev.behavior<boolean>(false),
  79. isUpdating: this.ev.behavior<boolean>(false),
  80. // TODO: should there be separate "updated" event?
  81. // Often, this is used to indicate that the state has updated
  82. // and it might not be the best way to react to state updates.
  83. isBusy: this.ev.behavior<boolean>(false)
  84. },
  85. interaction: {
  86. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  87. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  88. drag: this.ev.behavior<InteractivityManager.DragEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0, pageStart: Vec2(), pageEnd: Vec2() }),
  89. selectionMode: this.ev.behavior<boolean>(false)
  90. },
  91. labels: {
  92. highlight: this.ev.behavior<{ labels: ReadonlyArray<LociLabel> }>({ labels: [] })
  93. },
  94. layout: {
  95. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  96. },
  97. canvas3d: {
  98. initialized: this.canvas3dInit.pipe(filter(v => !!v), take(1))
  99. }
  100. } as const;
  101. readonly canvas3d: Canvas3D | undefined;
  102. readonly animationLoop = new PluginAnimationLoop(this);
  103. readonly layout = new PluginLayout(this);
  104. readonly representation = {
  105. structure: {
  106. registry: new StructureRepresentationRegistry(),
  107. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  108. },
  109. volume: {
  110. registry: new VolumeRepresentationRegistry(),
  111. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  112. }
  113. } as const;
  114. readonly query = {
  115. structure: {
  116. registry: new StructureSelectionQueryRegistry()
  117. }
  118. } as const;
  119. readonly dataFormats = new DataFormatRegistry();
  120. readonly builders = {
  121. data: new DataBuilder(this),
  122. structure: void 0 as any as StructureBuilder
  123. };
  124. build() {
  125. return this.state.data.build();
  126. }
  127. readonly helpers = {
  128. substructureParent: new SubstructureParentHelper(this),
  129. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  130. } as const;
  131. readonly managers = {
  132. structure: {
  133. hierarchy: new StructureHierarchyManager(this),
  134. component: new StructureComponentManager(this),
  135. measurement: new StructureMeasurementManager(this),
  136. selection: new StructureSelectionManager(this),
  137. focus: new StructureFocusManager(this),
  138. },
  139. volume: {
  140. hierarchy: new VolumeHierarchyManager(this)
  141. },
  142. interactivity: void 0 as any as InteractivityManager,
  143. camera: new CameraManager(this),
  144. animation: new PluginAnimationManager(this),
  145. snapshot: new PluginStateSnapshotManager(this),
  146. lociLabels: void 0 as any as LociLabelManager,
  147. toast: new PluginToastManager(this),
  148. asset: new AssetManager(),
  149. task: new TaskManager()
  150. } as const;
  151. readonly events = {
  152. log: this.ev<LogEntry>(),
  153. task: this.managers.task.events,
  154. canvas3d: {
  155. settingsUpdated: this.ev(),
  156. }
  157. } as const;
  158. readonly customModelProperties = new CustomProperty.Registry<Model>();
  159. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  160. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  161. readonly customStructureControls = new Map<string, { new(): PluginUIComponent<any, any, any> }>();
  162. readonly genericRepresentationControls = new Map<string, (selection: StructureHierarchyManager['selection']) => [StructureHierarchyRef[], string]>();
  163. /**
  164. * Used to store application specific custom state which is then available
  165. * to State Actions and similar constructs via the PluginContext.
  166. */
  167. readonly customState: unknown = Object.create(null);
  168. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  169. try {
  170. this.layout.setRoot(container);
  171. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  172. const antialias = !(this.config.get(PluginConfig.General.DisableAntialiasing) ?? false);
  173. const pixelScale = this.config.get(PluginConfig.General.PixelScale) || 1;
  174. (this.canvas3d as Canvas3D) = Canvas3D.fromCanvas(canvas, {}, { antialias, pixelScale });
  175. this.canvas3dInit.next(true);
  176. let props = this.spec.components?.viewport?.canvas3d;
  177. const backgroundColor = Color(0xFCFBF9);
  178. if (!props) {
  179. this.canvas3d?.setProps({ renderer: { backgroundColor } });
  180. } else {
  181. if (props.renderer?.backgroundColor === void 0) {
  182. props = produce(props, p => {
  183. if (p.renderer) p.renderer.backgroundColor = backgroundColor;
  184. else p.renderer = { backgroundColor };
  185. });
  186. }
  187. this.canvas3d?.setProps(props);
  188. }
  189. this.animationLoop.start();
  190. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  191. return true;
  192. } catch (e) {
  193. this.log.error('' + e);
  194. console.error(e);
  195. return false;
  196. }
  197. }
  198. readonly log = {
  199. entries: List<LogEntry>(),
  200. entry: (e: LogEntry) => this.events.log.next(e),
  201. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  202. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  203. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  204. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  205. };
  206. /**
  207. * This should be used in all transform related request so that it could be "spoofed" to allow
  208. * "static" access to resources.
  209. */
  210. readonly fetch = ajaxGet
  211. /** return true is animating or updating */
  212. get isBusy() {
  213. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  214. }
  215. get selectionMode() {
  216. return this.behaviors.interaction.selectionMode.value;
  217. }
  218. set selectionMode(mode: boolean) {
  219. this.behaviors.interaction.selectionMode.next(mode);
  220. }
  221. dataTransaction(f: (ctx: RuntimeContext) => Promise<void> | void, options?: { canUndo?: string | boolean, rethrowErrors?: boolean }) {
  222. return this.runTask(this.state.data.transaction(f, options));
  223. }
  224. clear(resetViewportSettings = false) {
  225. if (resetViewportSettings) this.canvas3d?.setProps(DefaultCanvas3DParams);
  226. return PluginCommands.State.RemoveObject(this, { state: this.state.data, ref: StateTransform.RootRef });
  227. }
  228. dispose() {
  229. if (this.disposed) return;
  230. this.commands.dispose();
  231. this.canvas3d?.dispose();
  232. this.ev.dispose();
  233. this.state.dispose();
  234. this.managers.task.dispose();
  235. this.layout.dispose();
  236. this.helpers.substructureParent.dispose();
  237. objectForEach(this.managers, m => (m as any)?.dispose?.());
  238. objectForEach(this.managers.structure, m => (m as any)?.dispose?.());
  239. this.disposed = true;
  240. }
  241. private initBehaviorEvents() {
  242. merge(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(u => {
  243. if (this.behaviors.state.isUpdating.value !== u) this.behaviors.state.isUpdating.next(u);
  244. });
  245. const timeoutMs = this.config.get(PluginConfig.General.IsBusyTimeoutMs) || 750;
  246. const isBusy = this.behaviors.state.isBusy;
  247. let timeout: any = void 0;
  248. const setBusy = () => {
  249. if (!isBusy.value) isBusy.next(true);
  250. };
  251. const reset = () => {
  252. if (timeout !== void 0) clearTimeout(timeout);
  253. timeout = void 0;
  254. };
  255. merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(v => {
  256. const isUpdating = this.behaviors.state.isUpdating.value;
  257. const isAnimating = this.behaviors.state.isAnimating.value;
  258. if (isUpdating || isAnimating) {
  259. if (!isBusy.value) {
  260. reset();
  261. timeout = setTimeout(setBusy, timeoutMs);
  262. }
  263. } else {
  264. reset();
  265. isBusy.next(false);
  266. }
  267. });
  268. this.behaviors.interaction.selectionMode.subscribe(v => {
  269. if (!v) {
  270. this.managers.interactivity?.lociSelects.deselectAll();
  271. }
  272. });
  273. }
  274. private initBuiltInBehavior() {
  275. BuiltInPluginBehaviors.State.registerDefault(this);
  276. BuiltInPluginBehaviors.Representation.registerDefault(this);
  277. BuiltInPluginBehaviors.Camera.registerDefault(this);
  278. BuiltInPluginBehaviors.Misc.registerDefault(this);
  279. merge(this.state.data.events.log, this.state.behaviors.events.log).subscribe(e => this.events.log.next(e));
  280. }
  281. private async initBehaviors() {
  282. let tree = this.state.behaviors.build();
  283. for (const cat of Object.keys(PluginBehavior.Categories)) {
  284. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  285. }
  286. // Init custom properties 1st
  287. for (const b of this.spec.behaviors) {
  288. const cat = PluginBehavior.getCategoryId(b.transformer);
  289. if (cat !== 'custom-props') continue;
  290. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  291. }
  292. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  293. tree = this.state.behaviors.build();
  294. for (const b of this.spec.behaviors) {
  295. const cat = PluginBehavior.getCategoryId(b.transformer);
  296. if (cat === 'custom-props') continue;
  297. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  298. }
  299. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  300. }
  301. private initCustomFormats() {
  302. if (!this.spec.customFormats) return;
  303. for (const f of this.spec.customFormats) {
  304. this.dataFormats.add(f[0], f[1]);
  305. }
  306. }
  307. private initDataActions() {
  308. for (const a of this.spec.actions) {
  309. this.state.data.actions.add(a.action);
  310. }
  311. }
  312. private initAnimations() {
  313. if (!this.spec.animations) return;
  314. for (const anim of this.spec.animations) {
  315. this.managers.animation.register(anim);
  316. }
  317. }
  318. private initCustomParamEditors() {
  319. if (!this.spec.customParamEditors) return;
  320. for (const [t, e] of this.spec.customParamEditors) {
  321. this.customParamEditors.set(t.id, e);
  322. }
  323. }
  324. async init() {
  325. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  326. this.initCustomFormats();
  327. this.initBehaviorEvents();
  328. this.initBuiltInBehavior();
  329. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  330. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  331. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  332. this.initDataActions();
  333. this.initAnimations();
  334. this.initCustomParamEditors();
  335. await this.initBehaviors();
  336. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  337. if (!isProductionMode) this.log.message(`Development mode enabled`);
  338. if (isDebugMode) this.log.message(`Debug mode enabled`);
  339. }
  340. constructor(public spec: PluginSpec) {
  341. // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
  342. // and freezing the params object causes "read-only exception"
  343. // TODO: is this the best place to do it?
  344. setAutoFreeze(false);
  345. }
  346. }