context.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 { List } from 'immutable';
  8. import { Canvas3D } from '../mol-canvas3d/canvas3d';
  9. import { CustomPropertyRegistry, CustomStructureProperty } from '../mol-model-props/common/custom-property-registry';
  10. import { StructureRepresentationRegistry } from '../mol-repr/structure/registry';
  11. import { VolumeRepresentationRegistry } from '../mol-repr/volume/registry';
  12. import { State, StateTransform, StateTransformer } from '../mol-state';
  13. import { Task, Progress } from '../mol-task';
  14. import { ColorTheme } from '../mol-theme/color';
  15. import { SizeTheme } from '../mol-theme/size';
  16. import { ThemeRegistryContext } from '../mol-theme/theme';
  17. import { Color } from '../mol-util/color';
  18. import { ajaxGet } from '../mol-util/data-source';
  19. import { LogEntry } from '../mol-util/log-entry';
  20. import { RxEventHelper } from '../mol-util/rx-event-helper';
  21. import { merge } from 'rxjs';
  22. import { BuiltInPluginBehaviors } from './behavior';
  23. import { PluginBehavior } from './behavior/behavior';
  24. import { PluginCommand, PluginCommands } from './command';
  25. import { PluginLayout, LeftPanelTabName } from './layout';
  26. import { PluginSpec } from './spec';
  27. import { PluginState } from './state';
  28. import { DataFormatRegistry } from './state/actions/data-format';
  29. import { StateTransformParameters } from '../mol-plugin-ui/state/common';
  30. import { LociLabelEntry, LociLabelManager } from './util/loci-label-manager';
  31. import { TaskManager } from './util/task-manager';
  32. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  33. import { StructureElementSelectionManager } from './util/structure-element-selection';
  34. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  35. import { ModifiersKeys } from '../mol-util/input/input-observer';
  36. import { isProductionMode, isDebugMode } from '../mol-util/debug';
  37. import { Model } from '../mol-model/structure';
  38. import { Interactivity } from './util/interactivity';
  39. import { StructureRepresentationHelper } from './util/structure-representation-helper';
  40. import { StructureSelectionHelper } from './util/structure-selection-helper';
  41. import { StructureOverpaintHelper } from './util/structure-overpaint-helper';
  42. import { PluginToastManager } from './state/toast';
  43. import { StructureMeasurementManager } from './util/structure-measurement';
  44. import { ViewportScreenshotHelper } from './util/viewport-screenshot';
  45. import { StructureRepresentationManager } from './state/representation/structure';
  46. interface Log {
  47. entries: List<LogEntry>
  48. readonly entry: (e: LogEntry) => void
  49. readonly error: (msg: string) => void
  50. readonly message: (msg: string) => void
  51. readonly info: (msg: string) => void
  52. readonly warn: (msg: string) => void
  53. }
  54. export class PluginContext {
  55. private disposed = false;
  56. private ev = RxEventHelper.create();
  57. private tasks = new TaskManager();
  58. readonly state = new PluginState(this);
  59. readonly commands = new PluginCommand.Manager();
  60. readonly events = {
  61. state: {
  62. cell: {
  63. stateUpdated: merge(this.state.dataState.events.cell.stateUpdated, this.state.behaviorState.events.cell.stateUpdated),
  64. created: merge(this.state.dataState.events.cell.created, this.state.behaviorState.events.cell.created),
  65. removed: merge(this.state.dataState.events.cell.removed, this.state.behaviorState.events.cell.removed),
  66. },
  67. object: {
  68. created: merge(this.state.dataState.events.object.created, this.state.behaviorState.events.object.created),
  69. removed: merge(this.state.dataState.events.object.removed, this.state.behaviorState.events.object.removed),
  70. updated: merge(this.state.dataState.events.object.updated, this.state.behaviorState.events.object.updated)
  71. },
  72. cameraSnapshots: this.state.cameraSnapshots.events,
  73. snapshots: this.state.snapshots.events,
  74. },
  75. log: this.ev<LogEntry>(),
  76. task: this.tasks.events,
  77. canvas3d: {
  78. initialized: this.ev(),
  79. settingsUpdated: this.ev()
  80. },
  81. interactivity: {
  82. propsUpdated: this.ev(),
  83. selectionUpdated: this.ev()
  84. }
  85. } as const
  86. readonly behaviors = {
  87. state: {
  88. isAnimating: this.ev.behavior<boolean>(false),
  89. isUpdating: this.ev.behavior<boolean>(false)
  90. },
  91. interaction: {
  92. hover: this.ev.behavior<Interactivity.HoverEvent>({ current: Interactivity.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  93. click: this.ev.behavior<Interactivity.ClickEvent>({ current: Interactivity.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 })
  94. },
  95. labels: {
  96. highlight: this.ev.behavior<{ entries: ReadonlyArray<LociLabelEntry> }>({ entries: [] })
  97. },
  98. layout: {
  99. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  100. }
  101. } as const
  102. readonly canvas3d: Canvas3D | undefined;
  103. readonly layout = new PluginLayout(this);
  104. readonly toasts = new PluginToastManager(this);
  105. readonly interactivity: Interactivity;
  106. readonly lociLabels: LociLabelManager;
  107. readonly structureRepresentation = {
  108. registry: new StructureRepresentationRegistry(),
  109. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  110. manager: void 0 as any as StructureRepresentationManager
  111. } as const
  112. readonly volumeRepresentation = {
  113. registry: new VolumeRepresentationRegistry(),
  114. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  115. } as const
  116. readonly dataFormat = {
  117. registry: new DataFormatRegistry()
  118. } as const
  119. readonly customModelProperties = new CustomPropertyRegistry<Model>();
  120. readonly customStructureProperties = new CustomStructureProperty.Registry();
  121. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  122. readonly helpers = {
  123. measurement: new StructureMeasurementManager(this),
  124. structureSelectionManager: new StructureElementSelectionManager(this),
  125. structureSelection: new StructureSelectionHelper(this),
  126. structureRepresentation: new StructureRepresentationHelper(this),
  127. structureOverpaint: new StructureOverpaintHelper(this),
  128. substructureParent: new SubstructureParentHelper(this),
  129. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  130. } as const;
  131. /**
  132. * Used to store application specific custom state which is then available
  133. * to State Actions and similar constructs via the PluginContext.
  134. */
  135. readonly customState: unknown = Object.create(null);
  136. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  137. try {
  138. this.layout.setRoot(container);
  139. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  140. (this.canvas3d as Canvas3D) = Canvas3D.fromCanvas(canvas, {}, t => this.runTask(t));
  141. this.events.canvas3d.initialized.next()
  142. this.events.canvas3d.initialized.isStopped = true // TODO is this a good way?
  143. const renderer = this.canvas3d!.props.renderer;
  144. PluginCommands.Canvas3D.SetSettings.dispatch(this, { settings: { renderer: { ...renderer, backgroundColor: Color(0xFCFBF9) } } });
  145. this.canvas3d!.animate();
  146. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  147. return true;
  148. } catch (e) {
  149. this.log.error('' + e);
  150. console.error(e);
  151. return false;
  152. }
  153. }
  154. readonly log: Log = {
  155. entries: List<LogEntry>(),
  156. entry: (e: LogEntry) => this.events.log.next(e),
  157. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  158. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  159. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  160. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  161. };
  162. /**
  163. * This should be used in all transform related request so that it could be "spoofed" to allow
  164. * "static" access to resources.
  165. */
  166. readonly fetch = ajaxGet
  167. runTask<T>(task: Task<T>) {
  168. return this.tasks.run(task);
  169. }
  170. requestTaskAbort(progress: Progress, reason?: string) {
  171. this.tasks.requestAbort(progress, reason);
  172. }
  173. dispose() {
  174. if (this.disposed) return;
  175. this.commands.dispose();
  176. this.canvas3d?.dispose();
  177. this.ev.dispose();
  178. this.state.dispose();
  179. this.tasks.dispose();
  180. this.layout.dispose();
  181. this.disposed = true;
  182. }
  183. applyTransform(state: State, a: StateTransform.Ref, transformer: StateTransformer, params: any) {
  184. const tree = state.build().to(a).apply(transformer, params);
  185. return PluginCommands.State.Update.dispatch(this, { state, tree });
  186. }
  187. updateTransform(state: State, a: StateTransform.Ref, params: any) {
  188. const tree = state.build().to(a).update(params);
  189. return PluginCommands.State.Update.dispatch(this, { state, tree });
  190. }
  191. private initBehaviorEvents() {
  192. merge(this.state.dataState.events.isUpdating, this.state.behaviorState.events.isUpdating).subscribe(u => {
  193. this.behaviors.state.isUpdating.next(u);
  194. });
  195. }
  196. private initBuiltInBehavior() {
  197. BuiltInPluginBehaviors.State.registerDefault(this);
  198. BuiltInPluginBehaviors.Representation.registerDefault(this);
  199. BuiltInPluginBehaviors.Camera.registerDefault(this);
  200. BuiltInPluginBehaviors.Misc.registerDefault(this);
  201. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  202. }
  203. private async initBehaviors() {
  204. const tree = this.state.behaviorState.build();
  205. for (const cat of Object.keys(PluginBehavior.Categories)) {
  206. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  207. }
  208. for (const b of this.spec.behaviors) {
  209. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  210. }
  211. await this.runTask(this.state.behaviorState.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  212. }
  213. private initDataActions() {
  214. for (const a of this.spec.actions) {
  215. this.state.dataState.actions.add(a.action);
  216. }
  217. }
  218. private initAnimations() {
  219. if (!this.spec.animations) return;
  220. for (const anim of this.spec.animations) {
  221. this.state.animation.register(anim);
  222. }
  223. }
  224. private initCustomParamEditors() {
  225. if (!this.spec.customParamEditors) return;
  226. for (const [t, e] of this.spec.customParamEditors) {
  227. this.customParamEditors.set(t.id, e);
  228. }
  229. }
  230. constructor(public spec: PluginSpec) {
  231. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  232. this.initBehaviorEvents();
  233. this.initBuiltInBehavior();
  234. this.initBehaviors();
  235. this.initDataActions();
  236. this.initAnimations();
  237. this.initCustomParamEditors();
  238. this.interactivity = new Interactivity(this);
  239. this.lociLabels = new LociLabelManager(this);
  240. (this.structureRepresentation.manager as StructureRepresentationManager)= new StructureRepresentationManager(this);
  241. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  242. if (!isProductionMode) this.log.message(`Development mode enabled`);
  243. if (isDebugMode) this.log.message(`Debug mode enabled`);
  244. }
  245. }