context.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { List } from 'immutable';
  7. import { Canvas3D } from 'mol-canvas3d/canvas3d';
  8. import { CustomPropertyRegistry } from 'mol-model-props/common/custom-property-registry';
  9. import { StructureRepresentationRegistry } from 'mol-repr/structure/registry';
  10. import { VolumeRepresentationRegistry } from 'mol-repr/volume/registry';
  11. import { State, StateTransform, StateTransformer } from 'mol-state';
  12. import { Task } from 'mol-task';
  13. import { ColorTheme } from 'mol-theme/color';
  14. import { SizeTheme } from 'mol-theme/size';
  15. import { ThemeRegistryContext } from 'mol-theme/theme';
  16. import { Color } from 'mol-util/color';
  17. import { ajaxGet } from 'mol-util/data-source';
  18. import { LogEntry } from 'mol-util/log-entry';
  19. import { RxEventHelper } from 'mol-util/rx-event-helper';
  20. import { merge } from 'rxjs';
  21. import { BuiltInPluginBehaviors } from './behavior';
  22. import { PluginBehavior } from './behavior/behavior';
  23. import { PluginCommand, PluginCommands } from './command';
  24. import { PluginLayout } from './layout';
  25. import { PluginSpec } from './spec';
  26. import { PluginState } from './state';
  27. import { DataFormatRegistry } from './state/actions/data-format';
  28. import { StateTransformParameters } from './ui/state/common';
  29. import { LociLabelEntry, LociLabelManager } from './util/loci-label-manager';
  30. import { TaskManager } from './util/task-manager';
  31. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  32. import { StructureElementSelectionManager } from './util/structure-element-selection';
  33. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  34. import { Representation } from 'mol-repr/representation';
  35. import { ModifiersKeys } from 'mol-util/input/input-observer';
  36. export class PluginContext {
  37. private disposed = false;
  38. private ev = RxEventHelper.create();
  39. private tasks = new TaskManager();
  40. readonly state = new PluginState(this);
  41. readonly commands = new PluginCommand.Manager();
  42. readonly events = {
  43. state: {
  44. cell: {
  45. stateUpdated: merge(this.state.dataState.events.cell.stateUpdated, this.state.behaviorState.events.cell.stateUpdated),
  46. created: merge(this.state.dataState.events.cell.created, this.state.behaviorState.events.cell.created),
  47. removed: merge(this.state.dataState.events.cell.removed, this.state.behaviorState.events.cell.removed),
  48. },
  49. object: {
  50. created: merge(this.state.dataState.events.object.created, this.state.behaviorState.events.object.created),
  51. removed: merge(this.state.dataState.events.object.removed, this.state.behaviorState.events.object.removed),
  52. updated: merge(this.state.dataState.events.object.updated, this.state.behaviorState.events.object.updated)
  53. },
  54. cameraSnapshots: this.state.cameraSnapshots.events,
  55. snapshots: this.state.snapshots.events,
  56. },
  57. log: this.ev<LogEntry>(),
  58. task: this.tasks.events,
  59. canvas3d: {
  60. settingsUpdated: this.ev()
  61. }
  62. };
  63. readonly behaviors = {
  64. state: {
  65. isAnimating: this.ev.behavior<boolean>(false),
  66. isUpdating: this.ev.behavior<boolean>(false)
  67. },
  68. canvas3d: {
  69. highlight: this.ev.behavior<Canvas3D.HighlightEvent>({ current: Representation.Loci.Empty, prev: Representation.Loci.Empty }),
  70. click: this.ev.behavior<Canvas3D.ClickEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0 })
  71. },
  72. labels: {
  73. highlight: this.ev.behavior<{ entries: ReadonlyArray<LociLabelEntry> }>({ entries: [] })
  74. }
  75. };
  76. readonly canvas3d: Canvas3D;
  77. readonly layout: PluginLayout = new PluginLayout(this);
  78. readonly lociLabels: LociLabelManager;
  79. readonly structureRepresentation = {
  80. registry: new StructureRepresentationRegistry(),
  81. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  82. }
  83. readonly volumeRepresentation = {
  84. registry: new VolumeRepresentationRegistry(),
  85. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  86. }
  87. readonly dataFormat = {
  88. registry: new DataFormatRegistry()
  89. }
  90. readonly customModelProperties = new CustomPropertyRegistry();
  91. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  92. readonly helpers = {
  93. structureSelection: new StructureElementSelectionManager(this),
  94. substructureParent: new SubstructureParentHelper(this)
  95. };
  96. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  97. try {
  98. this.layout.setRoot(container);
  99. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  100. (this.canvas3d as Canvas3D) = Canvas3D.create(canvas, container);
  101. PluginCommands.Canvas3D.SetSettings.dispatch(this, { settings: { backgroundColor: Color(0xFCFBF9) } });
  102. this.canvas3d.animate();
  103. return true;
  104. } catch (e) {
  105. this.log.error('' + e);
  106. console.error(e);
  107. return false;
  108. }
  109. }
  110. readonly log = {
  111. entries: List<LogEntry>(),
  112. entry: (e: LogEntry) => this.events.log.next(e),
  113. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  114. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  115. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  116. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  117. };
  118. /**
  119. * This should be used in all transform related request so that it could be "spoofed" to allow
  120. * "static" access to resources.
  121. */
  122. readonly fetch = ajaxGet
  123. runTask<T>(task: Task<T>) {
  124. return this.tasks.run(task);
  125. }
  126. dispose() {
  127. if (this.disposed) return;
  128. this.commands.dispose();
  129. this.canvas3d.dispose();
  130. this.ev.dispose();
  131. this.state.dispose();
  132. this.tasks.dispose();
  133. this.layout.dispose();
  134. this.disposed = true;
  135. }
  136. applyTransform(state: State, a: StateTransform.Ref, transformer: StateTransformer, params: any) {
  137. const tree = state.build().to(a).apply(transformer, params);
  138. return PluginCommands.State.Update.dispatch(this, { state, tree });
  139. }
  140. updateTransform(state: State, a: StateTransform.Ref, params: any) {
  141. const tree = state.build().to(a).update(params);
  142. return PluginCommands.State.Update.dispatch(this, { state, tree });
  143. }
  144. private initBehaviorEvents() {
  145. merge(this.state.dataState.events.isUpdating, this.state.behaviorState.events.isUpdating).subscribe(u => {
  146. this.behaviors.state.isUpdating.next(u);
  147. });
  148. }
  149. private initBuiltInBehavior() {
  150. BuiltInPluginBehaviors.State.registerDefault(this);
  151. BuiltInPluginBehaviors.Representation.registerDefault(this);
  152. BuiltInPluginBehaviors.Camera.registerDefault(this);
  153. BuiltInPluginBehaviors.Misc.registerDefault(this);
  154. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  155. }
  156. private async initBehaviors() {
  157. const tree = this.state.behaviorState.build();
  158. for (const cat of Object.keys(PluginBehavior.Categories)) {
  159. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  160. }
  161. for (const b of this.spec.behaviors) {
  162. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  163. }
  164. await this.runTask(this.state.behaviorState.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  165. }
  166. private initDataActions() {
  167. for (const a of this.spec.actions) {
  168. this.state.dataState.actions.add(a.action);
  169. }
  170. }
  171. private initAnimations() {
  172. if (!this.spec.animations) return;
  173. for (const anim of this.spec.animations) {
  174. this.state.animation.register(anim);
  175. }
  176. }
  177. private initCustomParamEditors() {
  178. if (!this.spec.customParamEditors) return;
  179. for (const [t, e] of this.spec.customParamEditors) {
  180. this.customParamEditors.set(t.id, e);
  181. }
  182. }
  183. constructor(public spec: PluginSpec) {
  184. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  185. this.initBehaviorEvents();
  186. this.initBuiltInBehavior();
  187. this.initBehaviors();
  188. this.initDataActions();
  189. this.initAnimations();
  190. this.initCustomParamEditors();
  191. this.lociLabels = new LociLabelManager(this);
  192. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  193. }
  194. }