context.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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 { Canvas3D } from 'mol-canvas3d/canvas3d';
  7. import { EmptyLoci, Loci } from 'mol-model/loci';
  8. import { Representation } from 'mol-repr/representation';
  9. import { StructureRepresentationRegistry } from 'mol-repr/structure/registry';
  10. import { State, Transform, Transformer } from 'mol-state';
  11. import { Task } from 'mol-task';
  12. import { ColorTheme } from 'mol-theme/color';
  13. import { SizeTheme } from 'mol-theme/size';
  14. import { ThemeRegistryContext } from 'mol-theme/theme';
  15. import { LogEntry } from 'mol-util/log-entry';
  16. import { RxEventHelper } from 'mol-util/rx-event-helper';
  17. import { merge } from 'rxjs';
  18. import { BuiltInPluginBehaviors } from './behavior';
  19. import { PluginCommand, PluginCommands } from './command';
  20. import { PluginSpec } from './spec';
  21. import { PluginState } from './state';
  22. import { TaskManager } from './util/task-manager';
  23. import { Color } from 'mol-util/color';
  24. import { LociLabelEntry, LociLabelManager } from './util/loci-label-manager';
  25. import { ajaxGet } from 'mol-util/data-source';
  26. import { CustomPropertyRegistry } from './util/custom-prop-registry';
  27. import { VolumeRepresentationRegistry } from 'mol-repr/volume/registry';
  28. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  29. import { PluginLayout } from './layout';
  30. import { List } from 'immutable';
  31. import { StateTransformParameters } from './ui/state/common';
  32. import { DataFormatRegistry } from './state/actions/basic';
  33. export class PluginContext {
  34. private disposed = false;
  35. private ev = RxEventHelper.create();
  36. private tasks = new TaskManager();
  37. readonly state = new PluginState(this);
  38. readonly commands = new PluginCommand.Manager();
  39. readonly events = {
  40. state: {
  41. cell: {
  42. stateUpdated: merge(this.state.dataState.events.cell.stateUpdated, this.state.behaviorState.events.cell.stateUpdated),
  43. created: merge(this.state.dataState.events.cell.created, this.state.behaviorState.events.cell.created),
  44. removed: merge(this.state.dataState.events.cell.removed, this.state.behaviorState.events.cell.removed),
  45. },
  46. object: {
  47. created: merge(this.state.dataState.events.object.created, this.state.behaviorState.events.object.created),
  48. removed: merge(this.state.dataState.events.object.removed, this.state.behaviorState.events.object.removed),
  49. updated: merge(this.state.dataState.events.object.updated, this.state.behaviorState.events.object.updated)
  50. },
  51. cameraSnapshots: this.state.cameraSnapshots.events,
  52. snapshots: this.state.snapshots.events,
  53. },
  54. log: this.ev<LogEntry>(),
  55. task: this.tasks.events,
  56. labels: {
  57. highlight: this.ev<{ entries: ReadonlyArray<LociLabelEntry> }>()
  58. },
  59. canvad3d: {
  60. settingsUpdated: this.ev()
  61. }
  62. };
  63. readonly behaviors = {
  64. canvas: {
  65. highlightLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  66. selectLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  67. },
  68. command: this.commands.behaviour
  69. };
  70. readonly canvas3d: Canvas3D;
  71. readonly layout: PluginLayout = new PluginLayout(this);
  72. readonly lociLabels: LociLabelManager;
  73. readonly structureRepresentation = {
  74. registry: new StructureRepresentationRegistry(),
  75. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  76. }
  77. readonly volumeRepresentation = {
  78. registry: new VolumeRepresentationRegistry(),
  79. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  80. }
  81. readonly dataFormat = {
  82. registry: new DataFormatRegistry()
  83. }
  84. readonly customModelProperties = new CustomPropertyRegistry();
  85. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  86. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  87. try {
  88. this.layout.setRoot(container);
  89. if (this.spec.initialLayout) this.layout.setProps(this.spec.initialLayout);
  90. (this.canvas3d as Canvas3D) = Canvas3D.create(canvas, container);
  91. PluginCommands.Canvas3D.SetSettings.dispatch(this, { settings: { backgroundColor: Color(0xFCFBF9) } });
  92. this.canvas3d.animate();
  93. return true;
  94. } catch (e) {
  95. this.log.error('' + e);
  96. console.error(e);
  97. return false;
  98. }
  99. }
  100. readonly log = {
  101. entries: List<LogEntry>(),
  102. entry: (e: LogEntry) => this.events.log.next(e),
  103. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  104. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  105. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  106. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  107. };
  108. /**
  109. * This should be used in all transform related request so that it could be "spoofed" to allow
  110. * "static" access to resources.
  111. */
  112. fetch(url: string, type: 'string' | 'binary' = 'string', body?: string): Task<string | Uint8Array> {
  113. return ajaxGet({ url, type, body });
  114. // const req = await fetch(url, { referrerPolicy: 'origin-when-cross-origin' });
  115. // return type === 'string' ? await req.text() : new Uint8Array(await req.arrayBuffer());
  116. }
  117. runTask<T>(task: Task<T>) {
  118. return this.tasks.run(task);
  119. }
  120. dispose() {
  121. if (this.disposed) return;
  122. this.commands.dispose();
  123. this.canvas3d.dispose();
  124. this.ev.dispose();
  125. this.state.dispose();
  126. this.tasks.dispose();
  127. this.layout.dispose();
  128. this.disposed = true;
  129. }
  130. applyTransform(state: State, a: Transform.Ref, transformer: Transformer, params: any) {
  131. const tree = state.tree.build().to(a).apply(transformer, params);
  132. return PluginCommands.State.Update.dispatch(this, { state, tree });
  133. }
  134. updateTransform(state: State, a: Transform.Ref, params: any) {
  135. const tree = state.build().to(a).update(params);
  136. return PluginCommands.State.Update.dispatch(this, { state, tree });
  137. }
  138. private initBuiltInBehavior() {
  139. BuiltInPluginBehaviors.State.registerDefault(this);
  140. BuiltInPluginBehaviors.Representation.registerDefault(this);
  141. BuiltInPluginBehaviors.Camera.registerDefault(this);
  142. BuiltInPluginBehaviors.Misc.registerDefault(this);
  143. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  144. }
  145. private async initBehaviors() {
  146. const tree = this.state.behaviorState.tree.build();
  147. for (const b of this.spec.behaviors) {
  148. tree.toRoot().apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  149. }
  150. await this.runTask(this.state.behaviorState.updateTree(tree, true));
  151. }
  152. private initDataActions() {
  153. for (const a of this.spec.actions) {
  154. this.state.dataState.actions.add(a.action);
  155. }
  156. }
  157. private initAnimations() {
  158. if (!this.spec.animations) return;
  159. for (const anim of this.spec.animations) {
  160. this.state.animation.register(anim);
  161. }
  162. }
  163. private initCustomParamEditors() {
  164. if (!this.spec.customParamEditors) return;
  165. for (const [t, e] of this.spec.customParamEditors) {
  166. this.customParamEditors.set(t.id, e);
  167. }
  168. }
  169. constructor(public spec: PluginSpec) {
  170. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  171. this.initBuiltInBehavior();
  172. this.initBehaviors();
  173. this.initDataActions();
  174. this.initAnimations();
  175. this.initCustomParamEditors();
  176. this.lociLabels = new LociLabelManager(this);
  177. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  178. }
  179. }