context.ts 16 KB

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