context.ts 11 KB

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