context.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /**
  2. * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { List } from 'immutable';
  8. import { Canvas3D } from '../mol-canvas3d/canvas3d';
  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, Progress } 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 { PluginCommands } from './commands';
  24. import { PluginCommandManager } from './command';
  25. import { PluginLayout, LeftPanelTabName } from './layout';
  26. import { PluginSpec } from './spec';
  27. import { PluginState } from './state';
  28. import { DataFormatRegistry } from '../mol-plugin-state/actions/data-format';
  29. import { StateTransformParameters } from '../mol-plugin-ui/state/common';
  30. import { LociLabelEntry, LociLabelManager } from '../mol-plugin-state/manager/loci-label';
  31. import { TaskManager } from './util/task-manager';
  32. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  33. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  34. import { ModifiersKeys } from '../mol-util/input/input-observer';
  35. import { isProductionMode, isDebugMode } from '../mol-util/debug';
  36. import { Model, Structure } from '../mol-model/structure';
  37. import { InteractivityManager } from '../mol-plugin-state/manager/interactivity';
  38. import { PluginToastManager } from './util/toast';
  39. import { StructureMeasurementManager } from '../mol-plugin-state/manager/structure/measurement';
  40. import { ViewportScreenshotHelper } from './util/viewport-screenshot';
  41. import { CustomProperty } from '../mol-model-props/common/custom-property';
  42. import { PluginConfigManager } from './config';
  43. import { DataBuilder } from '../mol-plugin-state/builder/data';
  44. import { StructureBuilder } from '../mol-plugin-state/builder/structure';
  45. import { StructureHierarchyManager } from '../mol-plugin-state/manager/structure/hierarchy';
  46. import { StructureSelectionManager } from '../mol-plugin-state/manager/structure/selection';
  47. import { TrajectoryFormatRegistry } from '../mol-plugin-state/formats/trajectory';
  48. import { StructureComponentManager } from '../mol-plugin-state/manager/structure/component';
  49. import { CameraManager } from '../mol-plugin-state/manager/camera';
  50. export class PluginContext {
  51. private disposed = false;
  52. private ev = RxEventHelper.create();
  53. private tasks = new TaskManager();
  54. readonly state = new PluginState(this);
  55. readonly commands = new PluginCommandManager();
  56. readonly events = {
  57. state: {
  58. cell: {
  59. stateUpdated: merge(this.state.dataState.events.cell.stateUpdated, this.state.behaviorState.events.cell.stateUpdated),
  60. created: merge(this.state.dataState.events.cell.created, this.state.behaviorState.events.cell.created),
  61. removed: merge(this.state.dataState.events.cell.removed, this.state.behaviorState.events.cell.removed),
  62. },
  63. object: {
  64. created: merge(this.state.dataState.events.object.created, this.state.behaviorState.events.object.created),
  65. removed: merge(this.state.dataState.events.object.removed, this.state.behaviorState.events.object.removed),
  66. updated: merge(this.state.dataState.events.object.updated, this.state.behaviorState.events.object.updated)
  67. },
  68. cameraSnapshots: this.state.cameraSnapshots.events,
  69. snapshots: this.state.snapshots.events,
  70. },
  71. log: this.ev<LogEntry>(),
  72. task: this.tasks.events,
  73. canvas3d: {
  74. initialized: this.ev(),
  75. settingsUpdated: this.ev()
  76. }
  77. } as const
  78. readonly config = new PluginConfigManager(this.spec.config);
  79. readonly behaviors = {
  80. state: {
  81. isAnimating: this.ev.behavior<boolean>(false),
  82. isUpdating: this.ev.behavior<boolean>(false),
  83. isBusy: this.ev.behavior<boolean>(false)
  84. },
  85. interaction: {
  86. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: InteractivityManager.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  87. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: InteractivityManager.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 })
  88. },
  89. labels: {
  90. highlight: this.ev.behavior<{ entries: ReadonlyArray<LociLabelEntry> }>({ entries: [] })
  91. },
  92. layout: {
  93. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  94. }
  95. } as const
  96. readonly canvas3d: Canvas3D | undefined;
  97. readonly layout = new PluginLayout(this);
  98. readonly structureRepresentation = {
  99. registry: new StructureRepresentationRegistry(),
  100. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  101. } as const
  102. readonly volumeRepresentation = {
  103. registry: new VolumeRepresentationRegistry(),
  104. themeCtx: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  105. } as const
  106. readonly dataFormat = {
  107. trajectory: TrajectoryFormatRegistry(),
  108. registry: new DataFormatRegistry()
  109. } as const
  110. readonly builders = {
  111. data: new DataBuilder(this),
  112. structure: void 0 as any as StructureBuilder
  113. };
  114. readonly managers = {
  115. structure: {
  116. hierarchy: new StructureHierarchyManager(this),
  117. component: new StructureComponentManager(this),
  118. measurement: new StructureMeasurementManager(this),
  119. selection: new StructureSelectionManager(this)
  120. },
  121. interactivity: void 0 as any as InteractivityManager,
  122. camera: new CameraManager(this),
  123. lociLabels: void 0 as any as LociLabelManager,
  124. toast: new PluginToastManager(this)
  125. } as const
  126. readonly customModelProperties = new CustomProperty.Registry<Model>();
  127. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  128. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  129. readonly helpers = {
  130. substructureParent: new SubstructureParentHelper(this),
  131. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  132. } as const;
  133. /**
  134. * Used to store application specific custom state which is then available
  135. * to State Actions and similar constructs via the PluginContext.
  136. */
  137. readonly customState: unknown = Object.create(null);
  138. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  139. try {
  140. this.layout.setRoot(container);
  141. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  142. (this.canvas3d as Canvas3D) = Canvas3D.fromCanvas(canvas, {}, t => this.runTask(t));
  143. this.events.canvas3d.initialized.next()
  144. this.events.canvas3d.initialized.isStopped = true // TODO is this a good way?
  145. const renderer = this.canvas3d!.props.renderer;
  146. PluginCommands.Canvas3D.SetSettings(this, { settings: { renderer: { ...renderer, backgroundColor: Color(0xFCFBF9) } } });
  147. this.canvas3d!.animate();
  148. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  149. return true;
  150. } catch (e) {
  151. this.log.error('' + e);
  152. console.error(e);
  153. return false;
  154. }
  155. }
  156. readonly log = {
  157. entries: List<LogEntry>(),
  158. entry: (e: LogEntry) => this.events.log.next(e),
  159. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  160. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  161. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  162. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  163. };
  164. /**
  165. * This should be used in all transform related request so that it could be "spoofed" to allow
  166. * "static" access to resources.
  167. */
  168. readonly fetch = ajaxGet
  169. /** return true is animating or updating */
  170. get isBusy() {
  171. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  172. }
  173. runTask<T>(task: Task<T>) {
  174. return this.tasks.run(task);
  175. }
  176. dataTransaction(f: () => Promise<void> | void, options?: { canUndo?: boolean }) {
  177. return this.runTask(this.state.dataState.transaction(f, options));
  178. }
  179. requestTaskAbort(progress: Progress, reason?: string) {
  180. this.tasks.requestAbort(progress, reason);
  181. }
  182. dispose() {
  183. if (this.disposed) return;
  184. this.commands.dispose();
  185. this.canvas3d?.dispose();
  186. this.ev.dispose();
  187. this.state.dispose();
  188. this.tasks.dispose();
  189. this.layout.dispose();
  190. this.disposed = true;
  191. }
  192. applyTransform(state: State, a: StateTransform.Ref, transformer: StateTransformer, params: any) {
  193. const tree = state.build().to(a).apply(transformer, params);
  194. return PluginCommands.State.Update(this, { state, tree });
  195. }
  196. updateTransform(state: State, a: StateTransform.Ref, params: any) {
  197. const tree = state.build().to(a).update(params);
  198. return PluginCommands.State.Update(this, { state, tree });
  199. }
  200. private initBehaviorEvents() {
  201. merge(this.state.dataState.events.isUpdating, this.state.behaviorState.events.isUpdating).subscribe(u => {
  202. this.behaviors.state.isUpdating.next(u);
  203. });
  204. merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(() => {
  205. const isUpdating = this.behaviors.state.isUpdating.value;
  206. const isAnimating = this.behaviors.state.isAnimating.value;
  207. const isBusy = this.behaviors.state.isBusy;
  208. if ((isUpdating || isAnimating) && !isBusy.value) isBusy.next(true);
  209. else if (isBusy.value) isBusy.next(false);
  210. })
  211. }
  212. private initBuiltInBehavior() {
  213. BuiltInPluginBehaviors.State.registerDefault(this);
  214. BuiltInPluginBehaviors.Representation.registerDefault(this);
  215. BuiltInPluginBehaviors.Camera.registerDefault(this);
  216. BuiltInPluginBehaviors.Misc.registerDefault(this);
  217. merge(this.state.dataState.events.log, this.state.behaviorState.events.log).subscribe(e => this.events.log.next(e));
  218. }
  219. private async initBehaviors() {
  220. const tree = this.state.behaviorState.build();
  221. for (const cat of Object.keys(PluginBehavior.Categories)) {
  222. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  223. }
  224. for (const b of this.spec.behaviors) {
  225. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  226. }
  227. await this.runTask(this.state.behaviorState.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  228. }
  229. private initDataActions() {
  230. for (const a of this.spec.actions) {
  231. this.state.dataState.actions.add(a.action);
  232. }
  233. }
  234. private initAnimations() {
  235. if (!this.spec.animations) return;
  236. for (const anim of this.spec.animations) {
  237. this.state.animation.register(anim);
  238. }
  239. }
  240. private initCustomParamEditors() {
  241. if (!this.spec.customParamEditors) return;
  242. for (const [t, e] of this.spec.customParamEditors) {
  243. this.customParamEditors.set(t.id, e);
  244. }
  245. }
  246. constructor(public spec: PluginSpec) {
  247. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  248. this.initBehaviorEvents();
  249. this.initBuiltInBehavior();
  250. this.initBehaviors();
  251. this.initDataActions();
  252. this.initAnimations();
  253. this.initCustomParamEditors();
  254. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  255. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  256. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  257. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  258. if (!isProductionMode) this.log.message(`Development mode enabled`);
  259. if (isDebugMode) this.log.message(`Debug mode enabled`);
  260. }
  261. }