context.ts 8.7 KB

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