context.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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, StateTransform, StateTransformer } 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 { VolumeRepresentationRegistry } from 'mol-repr/volume/registry';
  27. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  28. import { PluginLayout } from './layout';
  29. import { List } from 'immutable';
  30. import { StateTransformParameters } from './ui/state/common';
  31. import { DataFormatRegistry } from './state/actions/volume';
  32. import { PluginBehavior } from './behavior/behavior';
  33. import { CustomPropertyRegistry } from 'mol-model-props/common/custom-property-registry';
  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. labels: {
  58. highlight: this.ev<{ entries: ReadonlyArray<LociLabelEntry> }>()
  59. },
  60. canvad3d: {
  61. settingsUpdated: this.ev()
  62. }
  63. };
  64. readonly behaviors = {
  65. canvas: {
  66. highlightLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  67. selectLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  68. },
  69. command: this.commands.behaviour
  70. };
  71. readonly canvas3d: Canvas3D;
  72. readonly layout: PluginLayout = new PluginLayout(this);
  73. readonly lociLabels: LociLabelManager;
  74. readonly structureRepresentation = {
  75. registry: new StructureRepresentationRegistry(),
  76. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  77. }
  78. readonly volumeRepresentation = {
  79. registry: new VolumeRepresentationRegistry(),
  80. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  81. }
  82. readonly dataFormat = {
  83. registry: new DataFormatRegistry()
  84. }
  85. readonly customModelProperties = new CustomPropertyRegistry();
  86. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  87. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  88. try {
  89. this.layout.setRoot(container);
  90. if (this.spec.initialLayout) this.layout.setProps(this.spec.initialLayout);
  91. (this.canvas3d as Canvas3D) = Canvas3D.create(canvas, container);
  92. PluginCommands.Canvas3D.SetSettings.dispatch(this, { settings: { backgroundColor: Color(0xFCFBF9) } });
  93. this.canvas3d.animate();
  94. return true;
  95. } catch (e) {
  96. this.log.error('' + e);
  97. console.error(e);
  98. return false;
  99. }
  100. }
  101. readonly log = {
  102. entries: List<LogEntry>(),
  103. entry: (e: LogEntry) => this.events.log.next(e),
  104. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  105. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  106. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  107. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  108. };
  109. /**
  110. * This should be used in all transform related request so that it could be "spoofed" to allow
  111. * "static" access to resources.
  112. */
  113. fetch(url: string, type: 'string' | 'binary' = 'string', body?: string): Task<string | Uint8Array> {
  114. return ajaxGet({ url, type, body });
  115. // const req = await fetch(url, { referrerPolicy: 'origin-when-cross-origin' });
  116. // return type === 'string' ? await req.text() : new Uint8Array(await req.arrayBuffer());
  117. }
  118. runTask<T>(task: Task<T>) {
  119. return this.tasks.run(task);
  120. }
  121. dispose() {
  122. if (this.disposed) return;
  123. this.commands.dispose();
  124. this.canvas3d.dispose();
  125. this.ev.dispose();
  126. this.state.dispose();
  127. this.tasks.dispose();
  128. this.layout.dispose();
  129. this.disposed = true;
  130. }
  131. applyTransform(state: State, a: StateTransform.Ref, transformer: StateTransformer, params: any) {
  132. const tree = state.build().to(a).apply(transformer, params);
  133. return PluginCommands.State.Update.dispatch(this, { state, tree });
  134. }
  135. updateTransform(state: State, a: StateTransform.Ref, params: any) {
  136. const tree = state.build().to(a).update(params);
  137. return PluginCommands.State.Update.dispatch(this, { state, tree });
  138. }
  139. private initBuiltInBehavior() {
  140. BuiltInPluginBehaviors.State.registerDefault(this);
  141. BuiltInPluginBehaviors.Representation.registerDefault(this);
  142. BuiltInPluginBehaviors.Camera.registerDefault(this);
  143. BuiltInPluginBehaviors.Misc.registerDefault(this);
  144. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  145. }
  146. private async initBehaviors() {
  147. const tree = this.state.behaviorState.build();
  148. for (const cat of Object.keys(PluginBehavior.Categories)) {
  149. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, props: { isLocked: true } });
  150. }
  151. for (const b of this.spec.behaviors) {
  152. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  153. }
  154. await this.runTask(this.state.behaviorState.updateTree(tree, true));
  155. }
  156. private initDataActions() {
  157. for (const a of this.spec.actions) {
  158. this.state.dataState.actions.add(a.action);
  159. }
  160. }
  161. private initAnimations() {
  162. if (!this.spec.animations) return;
  163. for (const anim of this.spec.animations) {
  164. this.state.animation.register(anim);
  165. }
  166. }
  167. private initCustomParamEditors() {
  168. if (!this.spec.customParamEditors) return;
  169. for (const [t, e] of this.spec.customParamEditors) {
  170. this.customParamEditors.set(t.id, e);
  171. }
  172. }
  173. constructor(public spec: PluginSpec) {
  174. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  175. this.initBuiltInBehavior();
  176. this.initBehaviors();
  177. this.initDataActions();
  178. this.initAnimations();
  179. this.initCustomParamEditors();
  180. this.lociLabels = new LociLabelManager(this);
  181. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  182. }
  183. }