context.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * Copyright (c) 2018-2019 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 } from '../mol-canvas3d/canvas3d';
  11. import { CustomProperty } from '../mol-model-props/common/custom-property';
  12. import { Model, Structure } from '../mol-model/structure';
  13. import { DataFormatRegistry } from '../mol-plugin-state/actions/data-format';
  14. import { DataBuilder } from '../mol-plugin-state/builder/data';
  15. import { StructureBuilder } from '../mol-plugin-state/builder/structure';
  16. import { TrajectoryFormatRegistry } from '../mol-plugin-state/formats/trajectory';
  17. import { CameraManager } from '../mol-plugin-state/manager/camera';
  18. import { InteractivityManager } from '../mol-plugin-state/manager/interactivity';
  19. import { LociLabelEntry, LociLabelManager } from '../mol-plugin-state/manager/loci-label';
  20. import { StructureComponentManager } from '../mol-plugin-state/manager/structure/component';
  21. import { StructureHierarchyManager } from '../mol-plugin-state/manager/structure/hierarchy';
  22. import { StructureMeasurementManager } from '../mol-plugin-state/manager/structure/measurement';
  23. import { StructureSelectionManager } from '../mol-plugin-state/manager/structure/selection';
  24. import { StateTransformParameters } from '../mol-plugin-ui/state/common';
  25. import { StructureRepresentationRegistry } from '../mol-repr/structure/registry';
  26. import { VolumeRepresentationRegistry } from '../mol-repr/volume/registry';
  27. import { State, StateBuilder, StateTree } from '../mol-state';
  28. import { Progress, Task } from '../mol-task';
  29. import { ColorTheme } from '../mol-theme/color';
  30. import { SizeTheme } from '../mol-theme/size';
  31. import { ThemeRegistryContext } from '../mol-theme/theme';
  32. import { Color } from '../mol-util/color';
  33. import { ajaxGet } from '../mol-util/data-source';
  34. import { isDebugMode, isProductionMode } from '../mol-util/debug';
  35. import { ModifiersKeys } from '../mol-util/input/input-observer';
  36. import { LogEntry } from '../mol-util/log-entry';
  37. import { RxEventHelper } from '../mol-util/rx-event-helper';
  38. import { BuiltInPluginBehaviors } from './behavior';
  39. import { PluginBehavior } from './behavior/behavior';
  40. import { PluginCommandManager } from './command';
  41. import { PluginCommands } from './commands';
  42. import { PluginConfigManager } from './config';
  43. import { LeftPanelTabName, PluginLayout } from './layout';
  44. import { PluginSpec } from './spec';
  45. import { PluginState } from './state';
  46. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  47. import { TaskManager } from './util/task-manager';
  48. import { PluginToastManager } from './util/toast';
  49. import { ViewportScreenshotHelper } from './util/viewport-screenshot';
  50. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  51. export class PluginContext {
  52. private disposed = false;
  53. private ev = RxEventHelper.create();
  54. private tasks = new TaskManager();
  55. readonly state = new PluginState(this);
  56. readonly commands = new PluginCommandManager();
  57. readonly events = {
  58. state: {
  59. cell: {
  60. stateUpdated: merge(this.state.data.events.cell.stateUpdated, this.state.behaviors.events.cell.stateUpdated),
  61. created: merge(this.state.data.events.cell.created, this.state.behaviors.events.cell.created),
  62. removed: merge(this.state.data.events.cell.removed, this.state.behaviors.events.cell.removed),
  63. },
  64. object: {
  65. created: merge(this.state.data.events.object.created, this.state.behaviors.events.object.created),
  66. removed: merge(this.state.data.events.object.removed, this.state.behaviors.events.object.removed),
  67. updated: merge(this.state.data.events.object.updated, this.state.behaviors.events.object.updated)
  68. },
  69. cameraSnapshots: this.state.cameraSnapshots.events,
  70. snapshots: this.state.snapshots.events,
  71. },
  72. log: this.ev<LogEntry>(),
  73. task: this.tasks.events,
  74. canvas3d: {
  75. initialized: this.ev(),
  76. settingsUpdated: this.ev(),
  77. }
  78. } as const
  79. readonly config = new PluginConfigManager(this.spec.config);
  80. readonly behaviors = {
  81. state: {
  82. isAnimating: this.ev.behavior<boolean>(false),
  83. isUpdating: this.ev.behavior<boolean>(false),
  84. isBusy: this.ev.behavior<boolean>(false)
  85. },
  86. interaction: {
  87. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: InteractivityManager.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  88. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: InteractivityManager.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 })
  89. },
  90. labels: {
  91. highlight: this.ev.behavior<{ entries: ReadonlyArray<LociLabelEntry> }>({ entries: [] })
  92. },
  93. layout: {
  94. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  95. }
  96. } as const
  97. readonly canvas3d: Canvas3D | undefined;
  98. readonly layout = new PluginLayout(this);
  99. readonly representation = {
  100. structure: {
  101. registry: new StructureRepresentationRegistry(),
  102. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  103. },
  104. volume: {
  105. registry: new VolumeRepresentationRegistry(),
  106. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  107. }
  108. } as const;
  109. readonly dataFormat = {
  110. trajectory: TrajectoryFormatRegistry(),
  111. // TODO: separate registries for format catgories
  112. registry: new DataFormatRegistry()
  113. } as const
  114. readonly builders = {
  115. data: new DataBuilder(this),
  116. structure: void 0 as any as StructureBuilder
  117. };
  118. readonly managers = {
  119. structure: {
  120. hierarchy: new StructureHierarchyManager(this),
  121. component: new StructureComponentManager(this),
  122. measurement: new StructureMeasurementManager(this),
  123. selection: new StructureSelectionManager(this)
  124. },
  125. interactivity: void 0 as any as InteractivityManager,
  126. camera: new CameraManager(this),
  127. lociLabels: void 0 as any as LociLabelManager,
  128. toast: new PluginToastManager(this)
  129. } as const
  130. readonly customModelProperties = new CustomProperty.Registry<Model>();
  131. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  132. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  133. readonly helpers = {
  134. substructureParent: new SubstructureParentHelper(this),
  135. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  136. } as const;
  137. /**
  138. * Used to store application specific custom state which is then available
  139. * to State Actions and similar constructs via the PluginContext.
  140. */
  141. readonly customState: unknown = Object.create(null);
  142. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  143. try {
  144. this.layout.setRoot(container);
  145. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  146. (this.canvas3d as Canvas3D) = Canvas3D.fromCanvas(canvas, {}, t => this.runTask(t));
  147. this.events.canvas3d.initialized.next()
  148. this.events.canvas3d.initialized.isStopped = true // TODO is this a good way?
  149. const renderer = this.canvas3d!.props.renderer;
  150. PluginCommands.Canvas3D.SetSettings(this, { settings: { renderer: { ...renderer, backgroundColor: Color(0xFCFBF9) } } });
  151. this.canvas3d!.animate();
  152. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  153. return true;
  154. } catch (e) {
  155. this.log.error('' + e);
  156. console.error(e);
  157. return false;
  158. }
  159. }
  160. readonly log = {
  161. entries: List<LogEntry>(),
  162. entry: (e: LogEntry) => this.events.log.next(e),
  163. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  164. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  165. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  166. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  167. };
  168. /**
  169. * This should be used in all transform related request so that it could be "spoofed" to allow
  170. * "static" access to resources.
  171. */
  172. readonly fetch = ajaxGet
  173. /** return true is animating or updating */
  174. get isBusy() {
  175. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  176. }
  177. runTask<T>(task: Task<T>) {
  178. return this.tasks.run(task);
  179. }
  180. dataTransaction(f: () => Promise<void> | void, options?: { canUndo?: string | boolean }) {
  181. return this.runTask(this.state.data.transaction(f, options));
  182. }
  183. updateDataState(tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions>) {
  184. return this.runTask(this.state.data.updateTree(tree, options));
  185. }
  186. requestTaskAbort(progress: Progress, reason?: string) {
  187. this.tasks.requestAbort(progress, reason);
  188. }
  189. dispose() {
  190. if (this.disposed) return;
  191. this.commands.dispose();
  192. this.canvas3d?.dispose();
  193. this.ev.dispose();
  194. this.state.dispose();
  195. this.tasks.dispose();
  196. this.layout.dispose();
  197. this.disposed = true;
  198. }
  199. private initBehaviorEvents() {
  200. merge(this.state.data.events.isUpdating, this.state.behaviors.events.isUpdating).subscribe(u => {
  201. this.behaviors.state.isUpdating.next(u);
  202. });
  203. merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(() => {
  204. const isUpdating = this.behaviors.state.isUpdating.value;
  205. const isAnimating = this.behaviors.state.isAnimating.value;
  206. const isBusy = this.behaviors.state.isBusy;
  207. if ((isUpdating || isAnimating) && !isBusy.value) isBusy.next(true);
  208. else if (isBusy.value) isBusy.next(false);
  209. })
  210. }
  211. private initBuiltInBehavior() {
  212. BuiltInPluginBehaviors.State.registerDefault(this);
  213. BuiltInPluginBehaviors.Representation.registerDefault(this);
  214. BuiltInPluginBehaviors.Camera.registerDefault(this);
  215. BuiltInPluginBehaviors.Misc.registerDefault(this);
  216. merge(this.state.data.events.log, this.state.behaviors.events.log).subscribe(e => this.events.log.next(e));
  217. }
  218. private async initBehaviors() {
  219. let tree = this.state.behaviors.build();
  220. for (const cat of Object.keys(PluginBehavior.Categories)) {
  221. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  222. }
  223. // Init custom properties 1st
  224. for (const b of this.spec.behaviors) {
  225. const cat = PluginBehavior.getCategoryId(b.transformer);
  226. if (cat !== 'custom-props') continue;
  227. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  228. }
  229. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  230. tree = this.state.behaviors.build();
  231. for (const b of this.spec.behaviors) {
  232. const cat = PluginBehavior.getCategoryId(b.transformer);
  233. if (cat === 'custom-props') continue;
  234. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  235. }
  236. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  237. }
  238. private initDataActions() {
  239. for (const a of this.spec.actions) {
  240. this.state.data.actions.add(a.action);
  241. }
  242. }
  243. private initAnimations() {
  244. if (!this.spec.animations) return;
  245. for (const anim of this.spec.animations) {
  246. this.state.animation.register(anim);
  247. }
  248. }
  249. private initCustomParamEditors() {
  250. if (!this.spec.customParamEditors) return;
  251. for (const [t, e] of this.spec.customParamEditors) {
  252. this.customParamEditors.set(t.id, e);
  253. }
  254. }
  255. constructor(public spec: PluginSpec) {
  256. // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
  257. // and freezing the params object causes "read-only exception"
  258. // TODO: is this the best place to do it?
  259. setAutoFreeze(false);
  260. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  261. this.initBehaviorEvents();
  262. this.initBuiltInBehavior();
  263. this.initBehaviors();
  264. this.initDataActions();
  265. this.initAnimations();
  266. this.initCustomParamEditors();
  267. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  268. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  269. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  270. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  271. if (!isProductionMode) this.log.message(`Development mode enabled`);
  272. if (isDebugMode) this.log.message(`Debug mode enabled`);
  273. }
  274. }