context.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. export class PluginContext {
  32. private disposed = false;
  33. private ev = RxEventHelper.create();
  34. private tasks = new TaskManager();
  35. readonly state = new PluginState(this);
  36. readonly commands = new PluginCommand.Manager();
  37. readonly events = {
  38. state: {
  39. cell: {
  40. stateUpdated: merge(this.state.dataState.events.cell.stateUpdated, this.state.behaviorState.events.cell.stateUpdated),
  41. created: merge(this.state.dataState.events.cell.created, this.state.behaviorState.events.cell.created),
  42. removed: merge(this.state.dataState.events.cell.removed, this.state.behaviorState.events.cell.removed),
  43. },
  44. object: {
  45. created: merge(this.state.dataState.events.object.created, this.state.behaviorState.events.object.created),
  46. removed: merge(this.state.dataState.events.object.removed, this.state.behaviorState.events.object.removed),
  47. updated: merge(this.state.dataState.events.object.updated, this.state.behaviorState.events.object.updated)
  48. },
  49. cameraSnapshots: this.state.cameraSnapshots.events,
  50. snapshots: this.state.snapshots.events,
  51. },
  52. log: this.ev<LogEntry>(),
  53. task: this.tasks.events,
  54. labels: {
  55. highlight: this.ev<{ entries: ReadonlyArray<LociLabelEntry> }>()
  56. },
  57. canvad3d: {
  58. settingsUpdated: this.ev()
  59. }
  60. };
  61. readonly behaviors = {
  62. canvas: {
  63. highlightLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  64. selectLoci: this.ev.behavior<{ loci: Loci, repr?: Representation.Any }>({ loci: EmptyLoci }),
  65. },
  66. command: this.commands.behaviour
  67. };
  68. readonly canvas3d: Canvas3D;
  69. readonly layout: PluginLayout = new PluginLayout(this);
  70. readonly lociLabels: LociLabelManager;
  71. readonly structureRepresentation = {
  72. registry: new StructureRepresentationRegistry(),
  73. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  74. }
  75. readonly volumeRepresentation = {
  76. registry: new VolumeRepresentationRegistry(),
  77. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  78. }
  79. readonly customModelProperties = new CustomPropertyRegistry();
  80. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  81. try {
  82. this.layout.setRoot(container);
  83. if (this.spec.initialLayout) this.layout.updateState(this.spec.initialLayout);
  84. (this.canvas3d as Canvas3D) = Canvas3D.create(canvas, container);
  85. PluginCommands.Canvas3D.SetSettings.dispatch(this, { settings: { backgroundColor: Color(0xFCFBF9) } });
  86. this.canvas3d.animate();
  87. return true;
  88. } catch (e) {
  89. this.log.error('' + e);
  90. console.error(e);
  91. return false;
  92. }
  93. }
  94. readonly log = {
  95. entries: List<LogEntry>(),
  96. entry: (e: LogEntry) => this.events.log.next(e),
  97. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  98. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  99. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  100. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  101. };
  102. /**
  103. * This should be used in all transform related request so that it could be "spoofed" to allow
  104. * "static" access to resources.
  105. */
  106. fetch(url: string, type: 'string' | 'binary' = 'string', body?: string): Task<string | Uint8Array> {
  107. return ajaxGet({ url, type, body });
  108. // const req = await fetch(url, { referrerPolicy: 'origin-when-cross-origin' });
  109. // return type === 'string' ? await req.text() : new Uint8Array(await req.arrayBuffer());
  110. }
  111. runTask<T>(task: Task<T>) {
  112. return this.tasks.run(task);
  113. }
  114. dispose() {
  115. if (this.disposed) return;
  116. this.commands.dispose();
  117. this.canvas3d.dispose();
  118. this.ev.dispose();
  119. this.state.dispose();
  120. this.tasks.dispose();
  121. this.disposed = true;
  122. }
  123. private initBuiltInBehavior() {
  124. BuiltInPluginBehaviors.State.registerDefault(this);
  125. BuiltInPluginBehaviors.Representation.registerDefault(this);
  126. BuiltInPluginBehaviors.Camera.registerDefault(this);
  127. BuiltInPluginBehaviors.Misc.registerDefault(this);
  128. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  129. }
  130. async initBehaviors() {
  131. const tree = this.state.behaviorState.tree.build();
  132. for (const b of this.spec.behaviors) {
  133. tree.toRoot().apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  134. }
  135. await this.runTask(this.state.behaviorState.update(tree, true));
  136. }
  137. initDataActions() {
  138. for (const a of this.spec.actions) {
  139. this.state.dataState.actions.add(a.action);
  140. }
  141. }
  142. applyTransform(state: State, a: Transform.Ref, transformer: Transformer, params: any) {
  143. const tree = state.tree.build().to(a).apply(transformer, params);
  144. return PluginCommands.State.Update.dispatch(this, { state, tree });
  145. }
  146. updateTransform(state: State, a: Transform.Ref, params: any) {
  147. const tree = state.build().to(a).update(params);
  148. return PluginCommands.State.Update.dispatch(this, { state, tree });
  149. }
  150. constructor(public spec: PluginSpec) {
  151. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  152. this.initBuiltInBehavior();
  153. this.initBehaviors();
  154. this.initDataActions();
  155. this.lociLabels = new LociLabelManager(this);
  156. // TODO: find a better solution for this.
  157. setTimeout(() => this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`), 500);
  158. }
  159. // settings = ;
  160. }