context.ts 9.8 KB

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