context.ts 11 KB

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